如何通过将x * x存储在"auto变量“中来更改它?我认为应该是相同的,而且我的测试表明类型、大小和值显然都是的。
但即使是x * x == (xx = x * x)也是假的。搞什么鬼?
(注:我知道IEEE 754和浮动和双工以及它们的常见问题,但这个问题让我感到困惑。)
#include <iostream>
#include <cmath>
#include <typeinfo>
#include <iomanip>
using namespace std;
int main() {
auto x = sqrt(11);
auto xx = x * x;
cout << boolalpha << fixed << setprecision(130);
cout << " xx == 11 " << ( xx == 11 ) << endl;
cout << "x * x == 11 " << (x * x == 11 ) << endl;
cout << "x * x == xx " << (x * x == xx ) << endl;
cout << "x * x == (xx = x * x) " << (x * x == (xx = x * x)) << endl;
cout << "x * x == x * x " << (x * x == x * x ) << endl;
cout << "types " << typeid(xx).name() << " " << typeid(x * x).name() << endl;
cout << "sizeofs " << sizeof(xx) << " " << sizeof(x * x) << endl;
cout << "xx " << xx << endl;
cout << "x * x " << x * x << endl;
}这是输出:
xx == 11 true
x * x == 11 false
x * x == xx false
x * x == (xx = x * x) false
x * x == x * x true
types d d
sizeofs 8 8
xx 11.0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000
x * x 11.0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000按此编制:
C:\Stefan\code\leetcode>g++ test4.cpp -static-libstdc++ -std=c++11 -o a.exe
C:\Stefan\code\leetcode>g++ --version
g++ (GCC) 4.8.1
Copyright (C) 2013 Free Software Foundation, Inc.
This is free software; see the source for copying conditions. There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.发布于 2016-02-17 04:31:34
这是双打通常不精确的现象。您没有提到您的硬件,但是在x86 (32位英特尔)上,计算过程中使用的临时程序是10字节长的双倍。x * x将是其中之一,而xx = x * x将被存储到一个8字节的双倍,然后加载回FPU进行比较。
如果打开优化或构建64位可执行文件,可能会得到不同的结果。
https://stackoverflow.com/questions/35447947
复制相似问题