Reputation: 8285
When I try to do this
double test = ((2 / 7) * 100);
it returns 0.
Does anybody know why this is and how to work around it?
Thanks
Upvotes: 0
Views: 1778
Reputation: 54
It's because of division. A division of two int numbers returns int number truncating any decimal points. Hence the result of the operation 2/7 will be 0.
It should be something like this:
double test = ((2.0 / 7.0) * 100.0);
Upvotes: 0
Reputation: 700152
You are doing integer math, and only converting to double
when you have the final result.
2 / 7 = 0
while
2.0 / 7.0 = 0.285714285714285
Do the math with double
values:
double test = ((2.0 / 7.0) * 100.0);
Upvotes: 0
Reputation: 109537
It's doing integer division because all the operands are integers.
To fix it, change at least one the operands to doubles like this:
double test = ((2.0 / 7.0) * 100.0);
Upvotes: 0
Reputation: 15692
You are dividing integers, so 2 / 7
becomes already 0
. Just try 2.0 / 7.0
and you'll get the correct result.
Upvotes: 0
Reputation: 887195
You're dividing integers.
If you want a non-integer result, at least one operand must be a float or double (or decimal).
You can do that by adding .00
to any of the literals to create a literal.
Upvotes: 5
Reputation: 3056
2 / 7 is integer division, and will return 0. Try this instead
2.0 / 7
(double) 2 / 7
Upvotes: 13