【问题标题】:The name "Count" does not exist in the current Context - How to fix [duplicate]当前上下文中不存在名称“Count”-如何修复[重复]
【发布时间】:2019-06-23 06:56:13
【问题描述】:

所以,我们正在课堂上制作一个分数计算器。目的是添加您输入的分数(即 40+75+87...等)以及计算您添加的分数数量,然后为您提供平均值。我不断收到一个错误,即名称“计数”不存在,而且它实际上也没有将我的分数加在一起,它只是将相同的数字放入(如果我输入 4 而不是 5,它不显示 9,它显示数字 5” . 谁能解释一下这个问题?

   public Form1()
    {
        InitializeComponent();

        int Count = 0;
        decimal Total = 0m;

    }

    private void btnAdd_Click(object sender, EventArgs e)
    {
        decimal Score = Convert.ToDecimal(txtScore.Text);
        decimal Total = Convert.ToDecimal (Score++);

        txtCount.Text = Count + 1;


        txtTotal.Text = Total.ToString();
        txtCount.Text = txtCount.ToString();
        txtAverage.Text = txtAverage.ToString();




    }

如果我输入分数“4”,预期的输出应该是“1”。一旦写入另一个分数,它应该显示“2”以及两个分数的总和(即输入“4”然后输入“5”,总分应该显示“9”)

【问题讨论】:

  • int Count = 0;decimal Total = 0m;放在构造函数public Form1() { ... }之外
  • 这段代码没有意义:txtCount.Text = txtCount.ToString();。应该是txtCount.Text = Count.ToString();
  • 你为什么要在这里将decimal 转换为decimaldecimal Total = Convert.ToDecimal (Score++);?应该是decimal Total = Convert.ToDecimal (txtTotal.Text);

标签: c# winforms


【解决方案1】:

您需要更改 Count 变量的范围。您当前的代码是在 Form1() 构造函数中创建局部变量 CountTotal。将其移出但仍位于同一类中 Form1 会更改其范围并使其在整个类中可访问。

int Count = 0;
decimal Total = 0m;

public Form1()
{
    InitializeComponent();
}

编辑:

您的要求看起来很简单。我敢打赌,这就是您想要实现的目标。确保您首先遵循上述代码。

private void btnAdd_Click(object sender, EventArgs e)
{
    decimal Score = Convert.ToDecimal(txtScore.Text);

    Total += Score;
    Count++;

    decimal Average = Total/Count;

    txtCount.Text = Count.ToString();
    txtTotal.Text = Total.ToString();
    txtAverage.Text = Average.ToString();
}

【讨论】:

  • 您可能想知道为什么我还将Total 变量移到Form1() 构造函数之外。由于 OP 不熟悉变量范围,因此我假设他不打算将其用作局部变量。
  • 非常感谢您对此的帮助!我也非常感谢您花时间来解释它!
  • 终于!非常感谢您的帮助!!!!
猜你喜欢
  • 2014-04-18
  • 1970-01-01
  • 2019-09-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-04-08
  • 1970-01-01
相关资源
最近更新 更多