int x = 73;
int y = 100;
double pct = x/y;
Why do I see 0 instead of .73?
int x = 73;
int y = 100;
double pct = x/y;
Why do I see 0 instead of .73?
It does the same in all C-like languages. If you divide two integers, the result is an integer. 0.73 is not an integer.
The common work-around is to multiply one of the two numbers by 1.0 to make it a floating point type, or just cast it.
Because the division is done with integers then converted to a double. Try this instead:
double pct = (double)x / (double)y;
because the operation is still on int type. Try double pct = (double)x / (double)y;
Integer division drops the fractional portion of the result. See: http://mathworld.wolfram.com/IntegerDivision.html
That’s because the type of the left hand operand of the division (x
) is of type int
, so the return type of x / y
is still int
. The fact that the destination variable is of type double
doesn’t affect the operation.
To get the intended result, you first have to cast (convert) x
to double
, as in:
double pct = (double)x / y;
It's important to understand the flow of execution in a line of code. You're correct to assume that setting the right side of the equation equal to double
(on the left side) will implicitly convert the solution as a double. However, the flow execution dicates that x/y is evaluated by itself before you even get to the double pct =
portion of the code. Thus, since two int
s are divided by each other, they will evaluate to an int
solution (in this case, rounding towards zero) before being implicitly converted to a double.
As other have noted, you'll need to cast the int
variables as double
s so the solution comes out as a double
and not as an int
.