gpt4 book ai didi

c++ - x*x != x*x 在自动变量中?

转载 作者:太空狗 更新时间:2023-10-29 20:22:59 26 4
gpt4 key购买 nike

x * x 如何通过将其存储在“auto 变量”中来更改?我认为它应该仍然是相同的,并且我的测试表明类型、大小和值显然都相同的。

但即使 x * x == (xx = x * x) 也是错误的。什么鬼?

(注意:我知道 IEEE 754 以及 float 和 double 的工作原理以及它们的常见问题,但这一个让我感到困惑。)

#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.

最佳答案

这是 double 常见的不精确。你没有提到你的硬件,但在 x86(32 位英特尔)上,计算期间使用的临时文件是 10 字节长的 double 。 x * x 将是其中之一,而 xx = x * x 在加载回 FPU 进行比较之前将存储为 8 字节 double 。

如果打开优化或构建 64 位可执行文件,您可能会得到不同的结果。

关于c++ - x*x != x*x 在自动变量中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35447947/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com