【发布时间】:2019-10-08 13:32:40
【问题描述】:
第 1 部分:我将创建一个程序,它将文件的内容读入数组,并在 ListBox 控件中显示数组的内容,并计算并显示数组值的总和。 - 完成那部分
第 2 部分:计算平均值、最高值和最低值并将它们显示在标签控件中。
我是编码新手,所以我做不了太多,我求助于堆栈溢出
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 SalesAnalysis
{
public partial class SalesAnalysisApplication : Form
{
public SalesAnalysisApplication()
{
InitializeComponent();
}
private void salesAnalysisButton_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;
//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++)
{
salesListBox.Items.Add(sales[index]);
}
//Calculate the sum of all values
for (int index = 0; index < sales.Length; index++)
{
totalSales += sales[index];
}
//display total of all values
salesListBox.Items.Add("Total =" + totalSales);
//Determine the average sales from the array
for (int index = 0; index < sales.Length; index++)
{
//calculate the average
averageSales = totalSales / 7;
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
private void Clear_Click(object sender, EventArgs e)
{
//Clear all fields
salesListBox.Items.Clear();
averageResultsLabel.Text = "";
highestResultsLabel.Text = "";
lowestResultsLabel.Text = "";
}
private void exitButton_Click(object sender, EventArgs e)
{
//close form
this.Close();
}
}
}
【问题讨论】:
-
您只需使用 IEnumerbale 的扩展方法即可完成所有这些操作
-
也许,您无能为力,但您始终可以将问题拆分为更小的部分。例如,您要询问三个不同的值:从一个开始,即平均值。第二步:你已经知道如何为标签赋值,你只需要计算数组元素的平均值,这里已经问过这个问题:how can i return the sum , average of an int array
-
decimal[] sales = File.ReadLines("Sales.txt").Select(line => decimal.Parse(line)).ToArray();- 您不必使用流 -
@MongZhu 谢谢大佬,好记号,谢谢你!