如何计算数组中的“平均”值,“最高”值和“最低”值? C#

时间:2019-05-22 06:18:04

标签: c# arrays winforms

PART 1:我要创建一个程序,该程序将文件的内容读取到数组中,并在ListBox控件中显示该数组的内容,然后计算并显示该数组的总值。 -完成该部分

PART 2:计算平均值,最高值和最低值,并将它们显示在Label控件中。

我是编码的新手,所以我不能做很多事情,我转向堆栈溢出寻求帮助

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();
    }
}

}

4 个答案:

答案 0 :(得分:6)

您可以使用linq进行此操作,例如:

    var list=Enumerable.Range(0,1000);

    var average = list.Average();

    var highest = list.Max()

    var smallest= list.Min()

    var total= list.Sum()

P.S不要忘记添加using System.Linq;

答案 1 :(得分:1)

非linq方法。

您有一个sales.Length和一个totalSales。因此,您有一个averageSales

对于最大值和最小值,当您处于for循环中

for (int index = 0; index < sales.Length; index ++ 
  {
    if (sales
  }

仅基于if语句分配值。像这样:

if (sales[index] > highestSales) 
{
  highestSales = sales[index];
}
if (sales[index] < lowestSales)
{
  lowestSales = sales[index];
}

答案 2 :(得分:0)

首先将Decimal数组转换为List。

List<decimal> lst = sales.OfType<decimal>().ToList(); // Convert to List.

然后按照Linq操作进行操作。

lst.Average(); lst.Min(); 

答案 3 :(得分:0)

如果您喜欢旧的 loop (而不是 Linq ),则可以尝试File.ReadLinesforeach

  decimal max = 0;
  decimal min = 0;
  decimal sum = 0;
  int count = 0;      

  foreach(string line in File.ReadLines("Sales.txt")) {
    decimal value = decimal.Parse(line);

    salesListBox.Items.Add(value);

    if (count == 0 || value > max)
      max = value;

    if (count == 0 || value < min)
      min = value;

    sum += value;
    count += 1;   
  } 

  decimal average = sum / count; 

  averageResultsLabel.Text = average.ToString("f2");
  highestResultsLabel.Text = max.ToString();
  lowestResultsLabel.Text = min.ToString();

这里我们根本不需要创建任何数组。如果您坚持使用数组,那么简单的 Linq 可以帮助

  decimal[] sales = File
    .ReadLines("Sales.txt")
    .Select(line => decimal.Parse(line))
    .ToArray();

foreach

  foreach(decimal value in sales) {
    salesListBox.Items.Add(value);
    ... 
  }