【问题标题】:Logical error in display/math not displaying initial result显示/数学中的逻辑错误未显示初始结果
【发布时间】:2020-02-19 03:27:45
【问题描述】:

我有一个学校的人口估算程序,结果不显示第一组结果。这是代码。

private void Button1_Click(object sender, EventArgs e)
{
    double startingPop;
    double increasePer;
    double numDays;

    const int INTERVAL = 1;

    if (double.TryParse(textBox1.Text, out startingPop))
    {
        if (double.TryParse(textBox2.Text, out increasePer))
        {
            if (double.TryParse(textBox3.Text, out numDays))
            {
                for (int i = 1; i <= numDays; i += INTERVAL)
                {
                    startingPop = (startingPop * (increasePer / 100) + startingPop);
                    Results.Items.Add("After " + i + " days, the amount of organisms is " + startingPop);
                }
            }
        }
    }
}

private void Button2_Click(object sender, EventArgs e)
{
    this.Close();
}

private void Button3_Click(object sender, EventArgs e)
{
    textBox1.Text = "";
    textBox2.Text = "";
    textBox3.Text = "";
    Results.Items.Clear();
}

我希望它显示第 1 天 2 个生物体,而不是显示第一个计算增加百分比,即(第 1 天 2.6)。我知道这可能非常明显,所以我道歉。感谢您的洞察力。

【问题讨论】:

  • 文本框的值是多少?
  • 看起来你需要做的只是交换for循环内的两行。话虽如此,您确定这是一个逻辑错误吗?换句话说,您确定 1天后”,人口应该仍然与起始人口相同吗?
  • 不,我需要它在第 1 天显示起始流行音乐,然后在应用增加后的几天显示流行音乐。 startPop 变量也是估计的人口。它应该像这样显示第 1 天 2 生物第 2 天 2.6 生物第 3 天 3.38 等,目前显示为第 1 天 2.6。

标签: c# math return return-value


【解决方案1】:

如果我正确理解您的问题,您的代码应该如下所示:

private void button1_Click(object sender, EventArgs e)
{
    double startingPop;
    double increasePer;
    double numDays;

    const int INTERVAL = 1;

    if (double.TryParse(textBox1.Text, out startingPop) &&
        double.TryParse(textBox2.Text, out increasePer) &&
        double.TryParse(textBox3.Text, out numDays))
    {
        Results.Items.Add("On the first day, the amount of organisms is " + startingPop);

        for (int i = 1; i <= numDays; i += INTERVAL)
        {
            startingPop = (startingPop * (increasePer / 100) + startingPop);
            Results.Items.Add("After " + i + " day(s), the amount of organisms is " + startingPop);
        }
    }
}

我对代码所做的更改:

  • 使用&amp;&amp; 运算符将三个if 语句合并为一个。
  • 在增加人口值之前打印人口值,这样下一个显示的值(读取为“1 天后”)将是下一个增加的值。
  • 为了使您的结果项在语法上正确,您可以在循环内的第二行中使用以下内容:

    string s = (i > 1 ? "s" : string.Empty);
    Results.Items.Add($"After {i} day{s}, the amount of organisms is {startingPop}.");
    

现在,假设textBox1textBox2textBox3 中的值为 2、30 和 5,显示的结果将是这样的:

【讨论】:

    猜你喜欢
    • 2015-02-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-10-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多