I’m trying to make a very simple program that will first read an integer N, after that it will read N datas, which are floats, and just put them back in the screen with 2 digits after the decimal point. It’s very simple, right? But it went wrong! Here is the source code :
#include<cstdio>
int main()
{
float d;
int n;
scanf("%d",&n);
while(n>0)
{
n--;
scanf("%f",&d);
printf("%.2f\n",d);
}
return 0;
}
When I put small values, such as 3.1 or 1.0, it works very well. But when I give big values such as -765057.71 or 978715.10 it prints different value. As of -765057.71 it prints -765057.69, and for the next one it prints 978715.13. WHY is this happening, and how I can fix this?
Primitive floating-point types do not have unlimited precision. There are some values that cannot be represented exactly, as you are seeing. You can mitigate this problem somewhat by using
doubleinstead offloat, but for large enough values you will still see the same issue.Other, more robust solutions include using a prebuilt arbitrary-precision library, rolling your own such library (if you’ve got some time to kill), representing your floating point values using two integers, one for the part before the decimal and one for the part after, or (if all you want to do is echo the number back out truncated to a given decimal position) using strings instead.
You may find this an interesting read: http://en.wikipedia.org/wiki/IEEE754