把浮点转为整型精度丢失,请看代码: 代码在VS2005的MFC项目下测试。 int n; float a = 10; float b = 0.001; float v = a / b; n = (int)v; // 执行后 n = 10000 n = (int)(a / b);// 执行后 n = 9999 我经常把转换写成一条语句,却得不到正确的结果,天啊! 估计是VC的编译器有问题。 请各位达人指点。
[Quote=引用 10 楼 nineforever 的回复:]
根据标准的规定,浮点运算的结果可以用更高的精度表示
The values of the floating operands and the results of floating expressions may be represented in greater
precision and range than that required by the type;
float b = 0.001; //不能精确表达,80bit的内部结果为+1.0000000474974513e-0003
n = (int)(a / b); // a/b的结果在内部是80bit,+9.9999995250255087e+0003
n = (int)v; …
[/Quote]
强,赞一个!已解惑,谢谢!
根据标准的规定,浮点运算的结果可以用更高的精度表示
The values of the floating operands and the results of floating expressions may be represented in greater
precision and range than that required by the type;
float b = 0.001; //不能精确表达,80bit的内部结果为+1.0000000474974513e-0003
n = (int)(a / b); // a/b的结果在内部是80bit,+9.9999995250255087e+0003
n = (int)v; // v的类型是float,10000.0。实际上内部作了+9.9999995250255087e+0003->10000.0的转换
两者的精度不同,所以转换为int的结果也不同