简体   繁体   English

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

[英]How to calculate the “average” value , “highest” value , and “Lowest” value in an array? C#

PART 1: I am to create a program that that reads a file's contents into an array, and displays the array's contents in a ListBox control, and calculates and displays the total of the array's values. 第1部分:我要创建一个程序,该程序将文件的内容读取到数组中,并在ListBox控件中显示该数组的内容,然后计算并显示数组值的总数。 - DONE THAT PART -完成该部分

PART 2: Calculate the average, Highest, and Lowest value and display them in a Label control. 第2部分:计算平均值,最高值和最低值,并将它们显示在Label控件中。

I'm new to coding so I couldn't do much, I turn to stack overflow for help 我是编码的新手,所以我不能做很多事情,我转向堆栈溢出寻求帮助

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

} }

You can use linq to do this for example: 您可以使用linq进行此操作,例如:

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

    var average = list.Average();

    var highest = list.Max()

    var smallest= list.Min()

    var total= list.Sum()

PS do not forget to add using System.Linq; PS不要忘记using System.Linq;添加using System.Linq;

The non-linq approach. 非Linq方法。

You have a sales.Length and a totalSales . 您有一个sales.LengthtotalSales Therefore, you have an averageSales . 因此,您具有averageSales

For max & min, while you are in the for loop 对于最大和最小,当您处于for循环中时

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

simply assign the value based on an if statement. 只需根据if语句分配值。 Something like: 就像是:

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

First convert ur Decimal array to List. 首先将ur Decimal数组转换为List。

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

Then Follow Linq Operations. 然后,按照Linq Operations。

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

In case you prefer good old loop (and no Linq ), you can try File.ReadLines and foreach : 如果您希望使用良好的旧循环 (而不使用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();

Here we don't have to create any array at all. 在这里,我们根本不必创建任何数组。 If you insist on having array a simple Linq can help 如果您坚持使用数组,那么简单的Linq可以帮助您

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

And foreach will be foreach

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM