c++ - 带有双移位和以下移位运算的 C/C++ 除法

标签 c++ c linux casting double

谁能解释一下为什么下面的代码会产生不同的结果?

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/

相关文章:

c++ - 如何在MFC中查找系统是否有我需要的字体?

linux - 是否可以更改导出到 Excel 时 HUE 使用的临时目录?

linux - 关于 SVN 结帐和网络问题的菜鸟问题

c - x86_64-pc-cygwin gcc编译错误

java - 如何将 Mat 转换为位图?(在 linux 上运行,而不是 android)

c++ - 保留两个具有相反值的 bool 类成员

c++ - 在控制台 C++ 中替换行

c++ - 将 super block 读入 C 结构

c - 定时器计数器为0并制作真正的第二个问题

C程序返回整数的数字之和