2016-01-21 35 views
0

我有程序代碼,它工作正常,除了幾行,程序必須找到最小值並打印它。C#找到框中的最小數量/字段

我有字符串字段/框「fieldEvidence.WorkingYears」。用戶必須編寫0到40之間的數字。 用戶可以將最多10個值或更少(對於10個人)。程序必須在控制檯中寫出「fieldEvidence.WorkingYears」中的最低值。如果值相同(可以說是2倍「30」),程序必須同時寫入兩者。

我現在有一些代碼,但它沒有以正確的方式工作,我應該改變什麼?

static void WorkingAge(Evidence[] fieldEvidence) 
    { 
     int maxYears = 40; 
     int counter = 0; 

     for (int i = 0; i < fieldEvidence.Length; i++) 
     { 
      if (maxYears > fieldEvidence[i].WorkingYears) 
      { 
       maxYears = fieldEvidence[i].WorkingYears; 
      } 
     } 
     //10 times for loop 
     for (int i = 0; i < 10; i++) 
     { 
      if (maxYears == fieldEvidence[i].WorkingYears) 
       counter++; 
     } 

     //if there is more than just one with the same value 
     if (counter > 1) 
     { 
      for (int i = 0; i < fieldEvidence.Length; i++) 
      { 
       if (maxYears == fieldEvidence[i].WorkingYears) 
       { 
        Console.WriteLine("Working years:{0}, fieldEvidence[i].WorkingYears); 
       } 
      } 
     } 
     else 
     { 
      for (int i = 0; i < fieldEvidence.Length; i++) 
      { 
       if (maxYears == fieldEvidence[i].WorkingYears) 
       { 
        Console.WriteLine("Working years:{0}, fieldEvidence[i].WorkingYears); 
       } 
      } 
     } 
    } 

例 用戶輸入:40,30,23,14,34 輸出:工作年:14

實施例2 用戶輸入:40,23,14,14,34 輸出:工作年限:14,14

+0

爲什麼不能使用計數器打印maxYears – novice

+0

爲什麼要打印'23'而不是'14'? – Kaz

+0

@Kaz,這是OP的問題。它不打印分鐘。 – mike

回答

0
static void WorkingAge(Evidence[] fieldEvidence) 
{ 
    // make a counter for the number of equal min's found 
    int counter = 1; 

    // start with min equal to the first age in the array 
    int min = fieldEvidence[0]; 

    // loop through array to find a possible new min 
    for (int i = 1; i < fieldEvidence.Length; i++) { 
     // if value < min, set min to this value and reset counter to 1 
     if (fieldEvidence[i].WorkingYears < min) { 
      min = fieldEvidence[i].WorkingYears; 
      counter = 1; 
     } 
     // if value equal to min, increase counter 
     else if (fieldEvidence[i].WorkingYears == min) 
      counter++; 
    } 

    // create your output string starting with the min 
    string output = min.ToString(); 
    // loop "counter" times to add multiple identical mins to string 
    for (int i = 1; i < counter; i++) { 
     output = output + ", " + min; 
    } 

    // output the string 
    Console.WriteLine("Working years: " + output); 

} 
+0

只是傾銷代碼不是很有幫助。請解釋你的代碼的作用。 – sr28

+0

添加評論。 – mike

+0

刪除downvote。 – sr28

1

我建議你使用LINQ - 它很簡單:

var example = new[]{40,30,23,14,34}.Select(year => new Evidence(year)).ToList(); 
var lowestVal = example.Min(x => x.WorkingYears); 
var result = example.Where(x => x.WorkingYears == lowestVal) 
        .Select(x => x.WorkingYears); 
Console.WriteLine("Working years: " + string.Join(", ", result));