0

So, I am a beginner in C programming and I encountered a problem while doing a particular mathematical operation using float data type in C. .

float i=(501.0/10.0);

when I print "i" without making any modifications it doesn't return a value = 50.1 but something like 50.099... but when I try to print the value as : printf("%0.2f",i); it returns the value as 50.10 Why am I encountering this problem and is it intended behaviour? If yes, please explain

abelenky
  • 63,815
  • 23
  • 109
  • 159
  • 1
    If you divide 2. by 3., sometimes you will get 0.666666, sometimes you will get 0.666667. Why is that? Because fractions like 1/3 and 2/3 cannot be represented exactly in decimal. But computer floating point typically uses *binary*, or base 2. And in binary, the fraction 1/10, or 0.1 in decimal, cannot be represented exactly, either. So there is literally no such number as 50.1 in computer floating point. The closest you're going to get is 50.099999 or 50.100001 or something like that. And then if you use `%.2f` in the format string, `printf` rounds it for you. – Steve Summit Nov 16 '22 at 16:30

0 Answers0