2016-10-14 109 views
3

http://i.stack.imgur.com/COOqs.png從銷售數據文件計算平均值?

銷售總額

使用命名Sales.txt附加的文件。創建一個應用程序,

讀取文件的內容到雙精度或十進制 顯示器陣列在ListBox控件數組的內容, 計算總數組的值,平均銷售額,銷售量最大,最小銷售 顯示總銷售,平均銷售,銷售額最高的和最小銷售 表應類似於以下內容:

我如何通過輸入到顯示總計/平均/高的圖像顯示/低價銷售部分數據正確相應的代碼? 我想自己做這個,所以如果你能提供一個可能與我正在做的事情有關的例子,那真的會有所幫助。 這是我已經能夠迄今爲止種類最多:

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

看看列表 - >你加載列表中的所有文件。之後,從列表中填充listBox。對列表List.Sort()進行排序。 List.Sum(),List.Sum()/ List.Count() - > avg,已排序的列表List.First() - > lowest,List.Last()max元素。詢問是否有不清楚的地方。 – mybirthname

回答

1

可以使用得到一個文件中的所有行

var lines = System.IO.File.ReadAllLines("../../Sales.txt"); 

您可以使用LINQ Select項目和解析陣列將字符串轉換爲小數點陣列

decimal[] sales = lines.Select(line => decimal.Parse(line)).ToArray(); 

從那裏您可以迭代數組並將它們添加到列表框中。

要查找小數數組的總數/平均數/高/低,可以再次使用linq擴展。

var total = sales.Sum(); 

var average = sales.Average(); 

var high = sales.Max(); 

var low = sales.Min(); 

這應該爲您提供要顯示的數據。希望這可以幫助。