Как рассчитать «среднее» значение, «самое высокое» значение и «самое низкое» значение в массиве? C # - PullRequest
0 голосов
/ 22 мая 2019

ЧАСТЬ 1: Я должен создать программу, которая считывает содержимое файла в массив и отображает содержимое массива в элементе управления ListBox, а также рассчитывает и отображает сумму значений массива. - СДЕЛАНО ЭТОЙ ЧАСТЬ

ЧАСТЬ 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 ]

6 голосов
/ 22 мая 2019

Вы можете использовать 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 голос
/ 22 мая 2019

Нелинейный подход.

У вас есть 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];
}
0 голосов
/ 22 мая 2019

Если вы предпочитаете старый добрый цикл (а не Linq ), вы можете попробовать File.ReadLines и foreach:

  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);
    ... 
  }      
0 голосов
/ 22 мая 2019

Сначала преобразовать массив r Decimal в список.

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

Затем выполните Linq Операции.

lst.Average(); lst.Min(); 
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...