2014-10-05 135 views
0

我陷入了從數組中獲取最小值的問題。每次運行它時,最小值仍爲零。 我知道索引必須減去一,但我不知道如何應用它的代碼。 對不起我的英文不好,我希望你們能幫助我!c#從數組中獲取最小值

public partial class Form1 : Form 
{ 
    int[] numbers = new int[99]; 
    int index = 0; 

    public Form1() 
    { 
     InitializeComponent(); 
    } 

    private void Form1_Load(object sender, EventArgs e) 
    { 

    } 
    public int Som() 
    { 
     //if the numbers are <99 they will be add to index. 
     int som = 0; 
     for (int i = 0; i < 99; i++) 
     { 
      som = som + numbers[i]; 
     } 
     return som; 
    } 
    public int Average() 
    { 
     // 
     int answersom = Som(); 
     int g = (answersom/index); 
      return g;  
    } 
    public int Max() 
    { 
     int Max = numbers[0]; 
     foreach (int number in numbers) 
     { 
      if (number > Max) 
      { 
       Max = number; 
      } 
     } 
     return Max; 
    } 
    public int Min() 
     {// array gets de value thats on 0 
      int Min = numbers[0]; 
      foreach (int number in numbers) 
      {// if the number is smaller then 0. 
       if (number < Min) 
       {// zero is the new number 
        Min = number; 
       } 

      } 
      return Min; 
     } 
    private void button1_Click(object sender, EventArgs e) 
    { 
     //if textbox doesnt contain numbers 
     if (textBox1.Text.All(chr => char.IsLetter(chr))) 
     { 
      //labeltext message 'please only fill in numbers' 
      label1.Text = "Vul alleen Cijfers in"; 
     } 
     //else 
     else 
     { 
      //is putting the numbers on the right spot of the array 
      numbers[index] = Convert.ToInt32(textBox1.Text); 
      //index will add each time. 
      index++; 
      label4.Text = Convert.ToString(Som()); 

     } 
     // 
     int g = Convert.ToInt32(textBox1.Text); 
     label5.Text = Convert.ToString(Average()); 
     { 

      label6.Text = Convert.ToString(Min()); 

      label7.Text = Convert.ToString(Max()); 

     } 
    } 
} 

}

回答

1

您可以輕鬆地使用LINQ使用,

使用System.Linq的;

int min = numbers.Min(); 
+0

爲什麼downvote?既然在覈心框架中已經有了一些東西,爲什麼要重塑自己? – Caramiriel 2014-10-05 11:46:13

+0

@ Caramiriel因爲這不能解決OP的問題。此外,他可能需要自己執行CS功能。 – Overv 2014-10-05 11:48:55

+0

@Overv True。雖然我認爲在這種情況下使用'List '會更容易,並使用'.Min()'。這只是重塑已經存在的東西。 – Caramiriel 2014-10-05 11:53:17

2

問題是,你總是用所有數字計算最小值,其中包括所有沒有用按鈕添加的數字的最小值。這就是爲什麼你的最小總是返回0,除非你添加99個數字。您需要將Min功能更改爲:

public int Min() { 
    int min = numbers[0]; 

    for (int i = 0; i < index; i++) { 
     int number = numbers[i]; 

     if (number < min) { 
      min = number; 
     } 
    } 

    return min; 
} 

正如你可以看到,該函數將現在只使用您所添加的數字計算最小(下面index指數),而不是所有數字在numbers陣列。

+0

非常感謝!它的最終工作即將到來T_T – sharpee 2014-10-05 11:53:37

相關問題