在列表中添加和显示变量

时间:2019-02-27 23:44:50

标签: c# winforms

这是一个分数计算器,当您输入介于1到100之间的分数时,它将存储该分数,显示已输入多少分数的计数以及平均值。我们应该让它使用List 添加数据,并使用foreach在消息框中显示。我尝试了多种不同的方法来添加和显示数据。当我执行scores.Add(无论如何)并尝试在“显示”的点击操作中调用它时,无论您输入多少次,它只会显示一条系统消息。我似乎无法使其正常工作。

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)                       
}

我尝试查看我的书中和此处的示例,但它们都是字符串。这是我所能获得的代码。我太困了!

1 个答案:

答案 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);
}