4

I'm trying to write a very simple program to calculate liquid nicotine strengh. Basically it's (strengh / nicStrengh) * amount. And it always comes out as 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;
}
CSDev
  • 3,177
  • 6
  • 19
  • 37
inFlux
  • 45
  • 5

2 Answers2

3

When you divide integer to integer the result is integer as well; e.g.

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

In your case strengh < amount that's why strengh / amount == 0. If you want result being int (say 3) put it as

  int result = strengh * amount / nicStrengh;

if you want double result (i.e. floating point value, say 3.15) let system know that you want floating point arithmetics:

  double result = (double)strengh / nicStrengh * amount;
Dmitry Bychenko
  • 180,369
  • 20
  • 160
  • 215
  • Or change `Convert.ToInt32()` to `Convert.ToDouble()` and any `int` to `double` to get floating point values all the way. – Rand Random Jul 26 '19 at 14:16
0

Try this

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

or this if result is with comma

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