2013-03-24 36 views
0

所以,基本上發生了什麼是我的代碼編譯和運行良好。但是當它運行存儲MinScore是和minName變量的值留0方法不會從數組中提取正確的數據

static void Main(string[] args) 
{ 
    int count = 0; 
    string[] names = new string[MAX_SIZE]; 
    int[] scores = new int[MAX_SIZE]; 

    string name; 
    int sum = 0; 
    int minScore = 0; 
    int maxScore = 0; 
    string minName = string.Empty; 
    string maxName = string.Empty; 
    string input; 
    int score; 

    Console.WriteLine("===============Saturday Night Coders================"); 
    Console.WriteLine("===============Bowling Score Program================"); 

    for (int i = 0; i < MAX_SIZE; i++) 
    { 
     Console.WriteLine("\n Please Enter a name and a score separated by a space"); 
     Console.WriteLine("Enter a blank line when finished"); 

     input = Console.ReadLine(); 

     if (input == "") 
     { 
     count = i; 
     Console.WriteLine("===========INPUT COMPLETE========="); 
     break; 
     } 

     string[] splitInput = input.Split(); 

     name = splitInput[0]; 
     score = int.Parse(splitInput[1]); 
     scores[i] = score; 
     names[i] = name; 
     sum += score; 
     if (minScore >= score) 
     { 
     minScore = score; 
     minName = name; 
     } 

     if (maxScore <= score) 
     { 
     maxScore = score; 
     maxName = name; 
     } 
     count = i + 1; 
    } 

     double average = sum/count; 
     Console.WriteLine("Here are the scores for this game"); 
     PrintScores(names, scores, count); 
     Console.WriteLine("Congratulations {0}, your score of {1} was the highest",maxName, maxScore); 
     Console.WriteLine("{0} , your score of {1} was the lowest, Maybe you should find a new hobby",minName, minScore); 
     Console.WriteLine("\n The team average was {0:f2}", average); 
     Console.WriteLine("Press any key to continue..."); 
     Console.ReadKey(); 
    } 

    static void PrintScores(string[] names, int[] scores, int count) 
    { 
     for (int i = 0; i < count; i++) 
     { 
      Console.Write("{0} \t {1}", names[i], scores[i]); 
      if (scores[i] == MAX_SCORE) 
      { 
       Console.WriteLine("*"); 
      } 
      else 
      { 
       Console.WriteLine(""); 
      } 
      Console.WriteLine(); 
     } 
    } 
} 

我似乎無法找出爲什麼for循環工程爲maxName和maxScore聲明,但不是minName和MinScore是語句。任何幫助深表感謝

回答

5

,而不是驗證碼:

int minScore = 0; 
int maxScore = 0; 

它是一種更好的做法是使用

int minScore = int.MaxValue; 
int maxScore = int.MinValue; 

因此,任何值小於初始MINVALUE小,任何值大於初始最高值。

+0

非常感謝您的完全解決問題。至於好的做法,我會確保我這樣做。 – 2013-03-24 23:05:41

2

我相信你可能已經在設置默認minScore做了邏輯上的錯誤,以0 如果是0決不會高於或等於任何得分大於0的情況下:

if (minScore >= score) 

實際上是

if (0 >= score) 

嘗試,而不是執行以下操作:

if (minScore == 0 || minScore >= score) 
+0

儘管您可能需要考慮其他代碼或對minScore使用不同的默認值,但您的最低分數爲0. – 2013-03-24 22:19:24