Nikitas Nikitas - 1 year ago 84
C Question

How to multiply floating point in ANSI C?

The following code:

float numberForFactorial;
float floatingPart = 1.400000;
int integralPart = 1;

numberForFactorial = ((floatingPart) - (float)integralPart) * 10;

printf("%d", (int)numberForFactorial);

Returns 3 instead of 4. Can you explain me why?

Answer Source

The float closest to 1.400000 is slightly less than 1.4. You can verify that by doing

printf("%0.8hf\n", floatingPart);

The result from ideone is 1.39999998. This means that 10 times the first digit after the decimal point is 3.

To avoid this issue, use rounding instead of truncation. One easy way to round is by adding half before truncation:

printf("%d", (int)(numberForFactorial + 0.5f));

will print 4 as you were expecting.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download