|
5啊哈币
本帖最后由 小明_V3IID 于 2017-4-29 13:05 编辑
#include <stdio.h>
#include <stdlib.h>
int main()
{
float a,b,c;
a=5.2;
b=3.1;
c=a+b;
printf("%f",c);
system("pause");
return 0;
}
为什么得出的不是8.3,而是8.299999呢?
同样的,第一个练习题1.2+2.3+3.4+4.5,得出的数字是11.4000000。
#include <stdio.h>
#include <stdlib.h>
int main()
{
float a,b,c,d,e;
a=1.2;
b=2.3;
c=3.4;
d=4.5;
e=a+b+c+d;
printf("%f",e);
system("pause");
return 0;
}
这是为什么呢,怎么改成正常的呢?
|
最佳答案
查看完整内容
浮点数在运算的时候会有精度丢失的问题。
比如说:
5.2用二进制表示的话是:101.0011(无限循环)。
但是float只有32位,因此部分数据被丢弃。同样的,3.1也会有部分数据丢失。
运算过程中就会有误差。输出的时候自然也是有误差。
可以这样修改:
#include
int main(){
float a,b,c;
a = 5.2;
b = 3.1;
c = a + b;
//只保留两位有效数字,同时会进行四舍五入操作,8.299999就会变成8.30
...
|