tags:

views:

433

answers:

6
int x = 73;  
int y = 100;  
double pct = x/y;

Why do I see 0 instead of .73?

+7  A: 

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.

Paul Tomblin
+32  A: 

Because the division is done with integers then converted to a double. Try this instead:

double pct = (double)x / (double)y;
Brian Ensink
Just for completeness: Converting one of the ints to double is enough, but it doesn't hurt to convert them both :)
schnaader
@schnaader You are absolutely correct.
Brian Ensink
+3  A: 

because the operation is still on int type. Try double pct = (double)x / (double)y;

DJ
+2  A: 

Integer division drops the fractional portion of the result. See: http://mathworld.wolfram.com/IntegerDivision.html

mmorrisson
+1  A: 

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;
fastijum
Which operand is double doesn't matter. `Either (double)73/100` or `73/(double)100` would work just fine. If one operand is a double, all integer types will be coerced to double.
David Thornley
+2  A: 

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 ints 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 doubles so the solution comes out as a double and not as an int.

Ben McCormack