2014-10-02 121 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阵列挑相关结果集。

希望它有帮助!