我最近遇到了这个与 cout.setf(ios::fixed) 有关的奇怪问题。我花了很长时间才找到原因,我想我会在这里询问以了解更多信息。
问题在于 - 使用 cout.setf(ios::fixed) 时,所有 float 都打印为十六进制数。为什么会这样? ios::base 的文档似乎并不暗示这会发生(至少对我而言)。我使用的是 g++ 5.3.0,下面粘贴的是一个最小示例和输出。
#include <iostream>
#include <complex>
using namespace std;
int main(int argc, char const *argv[])
{
complex<double> I(0.0, 1.0);
double pi = M_PI;
cout.setf(ios::scientific);
cout<<" I is "<<I<<endl;
cout<<" Exp(I Pi) "<<exp(I*pi)<<endl;
cout<<" Cos(Pi) "<<cos(pi)<<endl<<endl;
cout.setf(ios::fixed);
cout<<" I is "<<I<<endl;
cout<<" Exp(I Pi) "<<exp(I*pi)<<endl;
cout<<" Cos(Pi) "<<cos(pi)<<endl<<endl;
return 0;
}
输出
I is (0.000000e+00,1.000000e+00)
Exp(I Pi) (-1.000000e+00,1.224647e-16)
Cos(Pi) -1.000000e+00
I is (0x0p+0,0x1p+0)
Exp(I Pi) (-0x1p+0,0x1.1a62633145c07p-53)
Cos(Pi) -0x1p+0
请注意,当我更改后问题就消失了
cout.setf(ios::fixed);
到
cout.setf(ios::fixed, ios::floatfield);
最佳答案
因为你告诉它。
来自 setf
documentation on cppreference.com :
scientific - generate floating point types using scientific notation, or hex notation if combined with fixed: see
std::scientific
fixed - generate floating point types using fixed notation, or hex notation if combined with scientific: seestd::fixed
所以,当设置std::fixed
, 你需要取消设置 std::scientific
(这是你对 std::floatfield
的揭露,因为 std::floatfield
是 std::scientific|std::fixed|(std::scientific|std::fixed)|0
)以避免十六进制表示法。
关于c++ - 为什么 cout.setf(ios::fixed) 将我的 float 更改为十六进制?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36362077/