谁能解释一下为什么下面的代码会产生不同的结果?
double zaehler = -20;
double teiler = 0.08;
printf("ergebnis = %d \n", ((int) (zaehler/teiler)) << 7 );
printf("ergebnis = %d \n", (int) (-20/0.08) << 7 );
结果:
ergebnis = -31872
ergebnis = -32000
非常感谢
最佳答案
在 64 位和 80 位之间的可能差异范围内,非常小的舍入差异可以解释不同的输出。截断到 int 和移位的组合可以放大微小的差异。该程序:
#include <stdio.h>
int main(){
double zaehler = -20;
double teiler = 0.08;
printf("ergebnis = %d \n", (int) (zaehler/teiler) );
printf("ergebnis = %d \n", (int) (-20/0.08));
}
打印:
ergebnis = -249
ergebnis = -250
如果除法给出的答案即使比 250 稍小一点,截断为 int 也会得到 249。我建议四舍五入而不是截断。
Eclipse、MinGW:
Info: Internal Builder is used for build
g++ -O0 -g3 -Wall -c -fmessage-length=0 -o main.o "..\\main.cpp"
g++ -o TestCPP.exe main.o
关于c++ - 带有双移位和以下移位运算的 C/C++ 除法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21583037/