读取浮点值时出错 [英] Error reading float values
问题描述
我试图创建一个非常简单的程序,首先读取一个整数N,然后它将读取N个数据,它们是浮点数,然后将它们放回屏幕,小数点后2位。这很简单,对吧?但它错了!这里是源代码:
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;
}
当我输入小数值,例如3.1或1.0时, 。但是当我给出大值,如-765057.71或978715.10时,它打印不同的值。从-765057.71它打印-765057.69,并为下一个它打印978715.13。
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?
推荐答案
原始浮点类型没有无限精度。有一些值不能准确地表示,正如你看到的。你可以通过使用 double
而不是 float
来缓解这个问题,但是对于足够大的值,问题。
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 double
instead of float
, 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.
您可能会发现这是一个有趣的读物: http://en.wikipedia。 org / wiki / IEEE754
You may find this an interesting read: http://en.wikipedia.org/wiki/IEEE754
这篇关于读取浮点值时出错的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!