2013-04-15 23 views
-1

我目前正在做的一個UNI分配和感到很困惑如何 讓我的文本文件的內容爲十進制/雙陣列。如何讀入一個十進制數組C#

它自問這個問題- 「需要一個計算機程序從數據文件中讀取12個分數(十進制數),將它們存儲在一個數組中,然後計算中間10個分數的平均值,也就是說, 12個分數的最高和最低不被包括在平均計算「。我不知道如何解決這個錯誤 「不能隱式地將字符串[]轉換爲十進制[]」我相信這是因爲我使用的是文件。 ReadAllLines我認爲這是僅適用於使用字符串。

using System.IO; 

namespace ConsoleApplication9 
{ 
    class Program 
    { 
     static void Main(string[] args) 
     { 
      Decimal[] Score = File.ReadAllLines("Scores.txt"); 
      Decimal max = Score.Max(); 
      Decimal min = Score.Min(); 
      Console.WriteLine(max + min); 
      Decimal sum = Score.Sum(); 
      for (int index = 0; index < Score.Length; index++) 
      { 
       Console.WriteLine(Score[index]); 
      } 
      Console.ReadKey();  


      } 
    } 
} 

希望能對你有所幫助。 P.S.文本文件中只有數字。

回答

1

讀取您的文件將返回字符串值。你需要施放它們。我建議將鑄造值存儲在列表中,使用列表的ToArray()方法獲取最大值和最小值,並使用Count屬性獲取中間值:

String[] ScoreString = File.ReadAllLines("Scores.txt"); 
List<Decimal> ScoreList = new List<Decimal>(); 
Decimal mySum = 0; 
foreach(string s in ScoreString) 
{ ScoreList.Add(Convert.ToDecimal(s)); 
    mySum += Convert.ToDecimal(s); 
} 
decimal result = (mySum - ScoreList.ToArray().Max() - ScoreList.ToArray().Min())/(ScoreList.Count-2); 
Console.Write(result); 
1

是喜歡錢的貨幣,你需要交換/先轉換。

var allString = File.ReadAllLines("Scores.txt"); 
var arrString = allString.Split('\n'); 

for (int index = 0; index < arrString.Length; index++) 
    Score[index] = Decimal.Parse(arrString[index]); 
相關問題