Reputation: 45
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;
}
Upvotes: 4
Views: 74
Reputation:
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();
}
Upvotes: 0
Reputation: 186668
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;
Upvotes: 3