求问大佬,用codeblocks-17.12写下面的C语言代码,强制类型转换时,为什么第11行和第13行的结果不一样啊????
附原代码:
#include
#include
int main()
{
int a=200;
double b;
int c,d;
b=a*0.075;
printf("%f\n",b);
c=(int)(b);
printf("%d\n",c);
d=(int)(a*0.075);
printf("%d\n",d);
return 0;
}
因为浮点数存在误差,而强制转换就是取整,而不是四舍五入
如果正好是 14.999999999 就是 14
如果是 15.000000001 就是15
编译器可能会因为a是常量,而将a*0.75直接求出结果,写入程序。
编译器和运行执行了不同的cpu指令,所以误差不同
你要四舍五入可以
d=(int)(a*0.075+0.5);