int x = 73;
int y = 100;
double pct = x/y;
Why do I see 0 instead of .73?
Whatever you try to divide two int into double or float is not gonna happen. But you have tons of methods to make the calculation happen, just cast them into float or double before the calculation will be fine.
If either operand is a double, you'll get floating point arithmetic. If both operands are ints, you'll get integer arithmetic. 3.5/3 is double/int, so you get a double.
Integer Division and the Remainder Operator For example, the expression 7 / 4 evaluates to 1 and the expression 17 / 5 evaluates to 3. C provides the remainder operator, %, which yields the remainder after integer division. The remainder operator is an integer operator that can be used only with integer operands.
Because the division is done with integers then converted to a double. Try this instead:
double pct = (double)x / (double)y;
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With