'Expression in C is not giving required output It keeps giving Zero [duplicate]
void main()
{
int a = 5;
int b = 10;
int c;
c = (a / b) * 100;
//5/2=0.5
//0.5*100=50
printf("C value is : %d", c);
}
Why the output is Zero when the output should be 50. This is a question which I have been not caring for a long time. I wanna know what's happening behind that expression.
Solution 1:[1]
The expression a / b has integers for both operands, so integer division is performed which truncates any fractional portion of the result.
You'll need to cast one of the operands to a floating point type so that floating point division is carried out.
c = ((double)a / b) * 100;
Also, while in this particular case you should get the exact result you want, floating point arithmetic is not exact and rounding errors may occur.
Solution 2:[2]
Because the int value of 5 / 10 is 0 (0.5 gets rounded down). You need to use doubles or floats for this
void main()
{
float a = 5;
float b = 10;
float c;
c = (a / b) * 100;
//5/2=0.5
//0.5*100=50
printf("C value is : %f", c);
}
outputs 50.0
Solution 3:[3]
following the comments above, float should be the best answer.
void main()
{
int a = 5;
int b = 10;
int c;
c = a * 100 / b;
printf("C value is : %d", c);
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | dbush |
| Solution 2 | Filipe S. |
| Solution 3 | tiago calado |
