2014-10-02 119 views
0

我試圖建立一個使用C#的考試平地機。我對此很陌生,不太瞭解。我將使用哪些代碼添加最小和最大按鈕並添加標籤,說明它是最小值還是最大值?最小和最大按鈕和標籤

private void btnAdd_Click(object sender, EventArgs e) 
{ 
    int points; 
    try 
    { 
     points = int.Parse(txtPoints.Text); 
     lstPoints.Items.Add(points); 
     txtPoints.Clear(); 
     txtPoints.Focus(); 
     if (lstPoints.Items.Count == 12) 
     { 
      txtPoints.Enabled = false; 
      btnAdd.Enabled = false; 
     } 
     if (lblResult.Text != "") 
     { 
      lblResult.Text = ""; 
     } 
    } 
    catch 
    { 
     MessageBox.Show("Please enter only whole numbers"); 
     txtPoints.Clear(); 
     txtPoints.Focus(); 
    } 
} 

private void btnAvg_Click(object sender, EventArgs e) 
{  
    double total = 0; 
    for (int i = 0; i < lstPoints.Items.Count; i++) 
    { 
     total += (int)lstPoints.Items[i]; 
    } 
    total /= lstPoints.Items.Count; 
    lblResult.Text = total.ToString(); 
} 

private void btnClear_Click(object sender, EventArgs e) 
{ 
    lstPoints.Items.Clear(); 
    txtPoints.Enabled = true; 
    btnAdd.Enabled = true; 
} 
} 
} 
+0

'lstPoints.Items [i]'的類型是什麼? – Ofiris 2014-10-02 04:51:52

+0

哪條線發生異常? – Neel 2014-10-02 04:53:22

+0

它發生在這一行總數+ =(double)lstPoints.Items [i]; – Strongbad2143 2014-10-02 04:54:42

回答

1

希望這個作品

private void getMax() 
{ 
    int max=0; 
    for (int i = 0; i < lstPoints.Items.Count; i++) 
     { 
      if(max<(int)lstPoints.Items[i]) 
       { 
        max=(int)lstPoints.Items[i]; 
       } 
     } 

     lblResult.Text = max.ToString(); 
     } 

} 

private void getMin() 
{ 
    int min=(int)lstPoints.Items[0]; 
    for (int i = 1; i < lstPoints.Items.Count; i++) 
     { 
      if(min>(int)lstPoints.Items[i]) 
       { 
        min=(int)lstPoints.Items[i]; 
       } 
     } 

     lblResult.Text = min.ToString(); 
     } 

} 
+0

它的工作!謝謝。 – Strongbad2143 2014-10-02 05:38:57

+1

@ Strongbad2143然後接受他的答案 – meda 2014-10-02 06:18:36

0

有兩個possiblities我看到:

1)當你寫這樣的:

lstPoints.Items.Add(points); 

而不是增加List(Of Integer)使用SortedList。所以 列表將始終有排序的結果集。

2)使用Array.Sort()對記錄進行排序。

一旦你對記錄排序,第一個是最小值,最後一個是最大值(假設按升序排序)。

取出兩個按鈕和放置在窗體上,從屬性窗口中設置Text屬性到MinMax分別和在事件處理程序處理該事件Click和從lstPoints陣列挑相關結果集。

希望它有幫助!