相同的C ++'if'语句,在Linux / Windows上有不同的结果 [英] Same C++ 'if' statement, different results on Linux/Windows

查看:124
本文介绍了相同的C ++'if'语句,在Linux / Windows上有不同的结果的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  #include< p> cstdio> 
int main()
{
int a = 20,b = 14;
if(a * 1.0 / b *(a + 1)/(b + 1)== 2)printf(YES!);
else printf(NO!);
}

使用GCC 4.6.3在Ubuntu Linux 12.04上进行编译,输出 YES !

使用GCC 4.6.2在Windows 7上编译输出 NO!



然而,使用:

  double c = a * 1.0 / b *(a + 1)/(b 1); 
if(c == 2)printf(YES!);
...

将在两台机器上返回 YES!

为什么会出现这种差异?这是由编译器版本不匹配造成的吗(pathlevel版本号应该不重要)?为什么它在Windows机器上实际输出 NO!,而这种情况显然是正确的?解析方案

这只是一个猜测,你需要查看编译器的汇编输出来确定。



有可能一个编译器会在一个浮点寄存器,另一个将结果写入内存,将其从80位舍入到64位。也有可能是一个使用SSE,另一个不是。


I've found an interesting case where the same C++ code yields different results on different system.

#include <cstdio>
int main()
{
    int a=20, b=14;
    if(a*1.0/b*(a+1)/(b+1)==2) printf("YES!");
    else printf("NO!");
}

Compiled on Ubuntu Linux 12.04 using GCC 4.6.3 it outputs YES!

Compiled on Windows 7 using GCC 4.6.2 it outputs NO!

However, using:

double  c = a*1.0/b*(a+1)/(b+1);
if (c==2) printf("YES!");
...

will return YES! on both machines.

Any ideas why this difference emerges? Is this caused by compiler version mismatch (pathlevel version number shouldn't matter THAT much)? And why does it actually output NO! on the Windows machine, while this condition is obviously true?

解决方案

This is only a guess, you would need to look at the assembly output from the compiler to know for sure.

It is possible that one compiler left intermediate results in a floating-point register while the other wrote the results to memory, rounding it from 80 bits to 64. It's also possible that one uses SSE and the other does not.

这篇关于相同的C ++'if'语句,在Linux / Windows上有不同的结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆