The expression (a / b)
will evaluate to 0
, because it is an integer division, not a floating-point division. Multiplying 0
with 100
will yield 0
.
If you want to use floating-point numbers, you should change your program to the following:
int main( void )
{
double a = 5.0;
double b = 10.0;
double c;
c = (a / b) * 100.0;
printf( "C value is : %lf\n", c );
}
In order to enforce that floating-point division is used instead of integer division, it is actually sufficient to make one of the operands floating-point. This program will also work:
int main( void )
{
int a = 5;
int b = 10;
int c;
c = ( (double)a / b) * 100;
printf( "C value is : %d\n", c );
}
However, you should generally be careful of floating-point inaccuracy, which could cause a number to be rounded down, when converting it to an int
. In this particular case, this is not an issue, because 0.5
can be represented exactly in IEEE 754 floating-point format. But with other numbers, you will likely encounter issues, as described in the linked question.
In your case, it is actually possible to solve the problem without using floating-point numbers, by performing the multiplication with 100
before performing the division, by changing the line
c = (a / b) * 100;
to:
c = a * 100 / b;
That way, it will first calculate a * 100
, which is 500
, and then divide that by 10
.
However, this will only work in cases in which
- the division does not have any remainder, and
- the values of the sub-expressions are not too high that they are not representable as an
int
.
In other cases, it is probably better to use floating-point numbers.
However, it is possible to extend the range of an int
by using long int
or long long int
instead.