一段很似很简单的c代码,你能答对吗?
请输出以下程序的打印结果:
- C/C++ code
#include <stdio.h>#include <stdlib.h>void test1();void test2();void test3();void test4();int main(int argc, char* argv[]){ test1(); test2(); test3(); test4(); return 0;}void test1(){ float x = 0.0f; float y = 0.0f; x= 1.0f / y; if ( x == x ) printf("yes\n"); else printf("no\n");}void test2(){ float x = 0.0f; float y = 0.0f; float temp = 1.0f / y; x = temp - temp; if ( x == x ) printf("yes\n"); else printf("no\n");}void test3(){ float x = 0.0f; float y = 0.0f; float temp = 1.0f / y; x = temp + temp; if ( x == x ) printf("yes\n"); else printf("no\n");}void test4(){ float x = 0.0f; x= x / x; if ( x == x ) printf("yes\n"); else printf("no\n");}[解决办法]
yes
no
yes
no
[解决办法]
帮你贴一下
[解决办法]
经测试,即使是同一个编译器,选项不一样,结果也可能不一样。
我用Visual Studio 2008中文版,C++编译。
1、Release模式,“浮点模型”选为“快速”,结果为yes yes yes no
2、Release模式,“浮点模型”选为“精确”或者“严格”,结果为yes no yes no
3、Debug模式,“浮点模型”无论选择哪一样,结果都是yes no yes no
可能是在Release模式下,浮点模型为“快速”时,编译器进行了过度优化。
MSDN有文档描述。大意是:浮点模型为“快速”时,可能进行较多的优化,导致的结果就是,计算出来的值不一定那么精准,但是速度会快。浮点模型为“严格”时,按部就班照着标准来执行,但是速度慢。浮点模型为“精确”时,进行少量优化,尽可能在结果精准的前提下加快执行速度。