这是一个分数计算器,当您输入介于1到100之间的分数时,它将存储该分数,显示已输入多少分数的计数以及平均值。我们应该让它使用List
int Count = 0;
decimal Total = 0m;
List<int> scores = new List<int>();
private void btnAdd_Click(object sender, EventArgs e)
{
int Score = Convert.ToInt32(txtScore.Text);
scores.Add(1);
Total += Score;
Count++;
decimal Average = Total / Count;
txtTotal.Text = Total.ToString();
txtCount.Text = Count.ToString();
txtAverage.Text = Average.ToString();
txtScore.Focus();
}
private void btnClear_Click(object sender, EventArgs e)
{
int Count = 0;
decimal Total = 0m;
decimal Average = 0m;
int Score = 0;
scores.Clear();
txtScore.Text = Score.ToString();
txtAverage.Text = Average.ToString();
txtTotal.Text = Total.ToString();
txtCount.Text = Count.ToString();
}
private void btnDisplay_Click(object sender, EventArgs e)
{
foreach (int scoring in scores)
}
我尝试查看我的书中和此处的示例,但它们都是字符串。这是我所能获得的代码。我太困了!
答案 0 :(得分:1)
变量“总计”和“计数”基本上是无用的。试试这个:
private void btnAdd_Click(object sender, EventArgs e){
scores.Add(Convert.ToInt32(txtScore.Text));
txtTotal.Text = scores.Sum()+"";
txtCount.Text = scores.Count()+"";
txtAverage.Text = scores.Average()+"";
txtScore.Focus();
}
然后,在清除按钮中:
private void btnClear_Click(object sender, EventArgs e){
scores.Clear();
txtScore.Text = 0+"";
txtAverage.Text = 0+"";
txtTotal.Text = 0+"";
txtCount.Text = 0+"";
}
在显示按钮中:
private void btnDisplay_Click(object sender, EventArgs e){
string message = "";
int index = 0;
foreach (var score in scores) {
message += $"[{index++}]: {score}\n";
}
MessageBox.Show(message);
}