0

My program works for any value except 4.2 and I realised that the occurring problem is due to same kind of a mistake as this one:

#include <stdio.h>
int main(void)
{
    float x = 4.2;
    x = x * 100;
    printf("%f \n", x);
}

Why does this produce 419.99999 as output ? Thanks in advance AliSarp

1

Fact of choosing 4.2 by the staff is not chance, but to become aware of the problem of imprecision with float numbers, it is not an error but the inability of the computer to accurately store the numbers with several decimals due to the internal representation of these numbers (keep in mind that the computer really only manages numbers in base two), there are many answers here on the subject, your problem is solved simply by doing:

x = round(x * 100);

do not forget to include the library math.h

2
  • Thanks, this indeed solves my problem. But can you, just out of curiosity, elaborate on why I encounter such a problem ? Thanks. – Ali Sarp Mestcioglu Nov 20 '17 at 21:18
  • Some fractions cannot be precisely represented in decimal using a a finite number of digits, e.g. 1/3, computers using base 2 cannot precisely represent some floating point numbers. Floating point numbers can store a very large range of values, much larger than the range of an integer type of the same width due to the floating point bit model. However, you still have the same finite number of states those bits can hold. Not all real numbers inside the range can be stored precisely. (en.wikipedia.org/wiki/Floating_point) – MARS Nov 21 '17 at 20:39

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .