【发布时间】:2015-10-27 21:37:50
【问题描述】:
作业如下:
总销售额
使用名为 Sales.txt 的附件。创建一个应用程序
- 将文件内容读入双精度或十进制数组
- 在 ListBox 控件中显示数组的内容,
- 计算数组值、平均销售额、最大销售额、最小销售额的总和
- 显示总销售额、平均销售额、最高销售额和最低销售额
- 表单应类似于以下内容:
如何获取数据以显示Total/Average/High/Low销售部分的图片通过输入相应的代码正确显示?
我想自己做这件事,所以如果你能提供一个可能与我正在做的事情相关的例子,那真的很有帮助。
这是我目前能够输入的内容:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO;
namespace Total_Sales
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void displayButton_Click(object sender, EventArgs e)
{
//declaring array
const int SIZE = 100;
decimal[] sales = new decimal[SIZE];
//varible to hold amount stored in array
int count = 0;
decimal additionHolder = 0;
//declaring streamreader
StreamReader inputFile;
//opening the sales file
inputFile = File.OpenText("../../Sales.txt");
try
{
//pull contents from file into array while there is still items
//to pull and the array isnt full
while (!inputFile.EndOfStream && count < sales.Length)
{
sales[count] = decimal.Parse(inputFile.ReadLine());
count++;
}
//close the file
inputFile.Close();
//display contents in listbox
for (int index = 0; index < count; index++)
{
ListBox.Items.Add(sales[index]);
}
//add all the values
for (int index = 0; index < sales.Length; index++)
{
additionHolder += sales[index];
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
private void button1_Click(object sender, EventArgs e)
{
this.Close();
}
}
}
【问题讨论】:
-
您可以使用
List而不是array,您应该使用Linq来计算总数、最小值等。 -
我会试试的,谢谢。
-
我的教科书没有关于如何使用 linq 计算 C# 中的总数的任何内容。 amazon.com/Starting-Visual-2012-CD-Rom-Edition/dp/0133129454
-
使用
linq,如果我没记错你可以得到,例如,总和var total = sales.Sum();(不确定c#的代码是否正确,我在vb.net中编写) ... 最小值相同 (sales.Min();),平均值sales.Average();... 等等。 -
那么练习的目的是什么?学习 C#?学习winforms?您是否仅限于教科书中的材料?如果您不能使用
Linq,例如sales.Average(),您可以在阅读行数的同时跟踪最小和最大销售额并自己计算平均值。
标签: c# arrays variable-assignment