【问题标题】:Calcuation Result Always 0计算结果始终为 0
【发布时间】:2019-05-21 14:39:24
【问题描述】:

我正在尝试编写一个非常简单的程序来计算液体尼古丁强度。基本上是(strengh / nicStrengh) * amount。它总是以0 出现。

private void lblCalculate_Click(object sender, EventArgs e)
{
    int strengh = Convert.ToInt32(txtBoxDesiredStrengh.Text);
    int nicStrengh = Convert.ToInt32(txtBoxNicStrengh.Text);
    int amount = Convert.ToInt32(txtBoxAmount.Text);

    int result = strengh / nicStrengh * amount;

    string resultStr = result.ToString();

    label1.Text = resultStr;
}

【问题讨论】:

  • strengh / nicStrengh - 整数除法 - 写成amount * strengh / nicStrengh;
  • 尝试使用float 而不是int
  • 整数除法不会四舍五入,它会一直截断。因此,任何小于 1 的绝对分数始终为 0。

标签: c# calculation


【解决方案1】:

当您将 integer 划分为 integer 时,结果也是 integer;例如

 5 / 10 == 0       // not 0.5 - integer division
 5.0 / 10.0 == 0.5 // floating point division

在你的情况下strengh < amount 这就是为什么strengh / amount == 0。如果你想让result 成为int(比如3)把它写成

  int result = strengh * amount / nicStrengh;

如果你想要double result(即浮点值,比如3.15)让系统知道你想要浮点运算:

  double result = (double)strengh / nicStrengh * amount;

【讨论】:

  • 或将Convert.ToInt32() 更改为Convert.ToDouble() 并将任何int 更改为double 以获取浮点值。
【解决方案2】:

试试这个

private void button1_Click(object sender, EventArgs e)
    {
        int s = int.Parse(textBox1.Text);
        int n = int.Parse(textBox2.Text);
        int a = int.Parse(textBox3.Text);
        int result = (s / n) * a;
        label1.Text = result.ToString();
    }

如果结果是逗号,则为这个

 private void button1_Click(object sender, EventArgs e)
    {
        double s = double.Parse(textBox1.Text);
        double n = double.Parse(textBox2.Text);
        double a = double.Parse(textBox3.Text);
        double result = (s / n) * a;
        label1.Text = result.ToString();
    }

【讨论】:

    猜你喜欢
    • 2013-02-18
    • 1970-01-01
    • 2013-03-14
    • 2020-10-17
    • 2020-02-26
    • 1970-01-01
    • 1970-01-01
    • 2017-11-23
    相关资源
    最近更新 更多