【发布时间】:2016-02-17 04:26:01
【问题描述】:
如何通过将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.
【问题讨论】:
-
这与
auto无关。你所有的变量都被推导出为doubles,这只是浮点精度的问题。参见例如this. -
不相关,但您可以使用
std::cout<< std::boolalpha;将bools打印为true或false。这将为您节省一些代码。 -
@juanchopanza 谢谢,现在用了。
-
@vsoftco 您的链接似乎没有解释这一点。真的吗?
-
@vsoftco 那里的问题完全不同,那里的答案都没有解释我的问题。看来你不明白我的问题。
标签: c++ variables floating-point