计算结果始终为0

时间:2019-05-21 14:39:24

标签: c# calculation

我正在尝试编写一个非常简单的程序来计算液体尼古丁强度。基本上是(strengh / nicStrengh)*数量。并且总是以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;
    }

2 个答案:

答案 0 :(得分:2)

integer 除以 integer 时,结果也是 integer ;例如

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

在您的情况下,strengh < amountstrengh / amount == 0的原因。如果您想让result成为int(例如3),请输入

  int result = strengh * amount / nicStrengh;

如果您想要double result(即浮点数的值,说3.15),请让系统知道您需要浮点算术:

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

答案 1 :(得分:0)

尝试一下

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