第1个回答 2013-09-19
没能正确地做四舍五入是因为有效数字个数超出 double 允许范围,尾部数据不精确了。
有效数字少一点时,我的编译器(VC++ 6.0) 好像能做四舍五入。例如:
#include<stdio.h>
#include<stdlib.h>
main(){
double a,b,c,d;
a=1.12345;
b=-1.12345;
c=1.12344;
d=-1.12344;
printf("a=%.4lf b=%.4lf\n",a,b);
printf("c=%.4lf d=%.4lf\n",c,d);
a = 1.1234567890345;
b = -1.1234567890345;
c = 1.1234567890344;
d = -1.1234567890344;
printf("a=%.12lf b=%.12lf\n",a,b);
printf("c=%.12lf d=%.12lf\n",c,d);
return 0;
}
输出为:
a=1.1235 b=-1.1235
c=1.1234 d=-1.1234
a=1.123456789035 b=-1.123456789035
c=1.123456789034 d=-1.123456789034
====
编译器 是否总能正确地做四舍五入,没考证过。
通常,考虑数的正负,把某位绝对值加 5, 自己处理 四舍五入 为妥。本回答被提问者采纳