我最近遇到了这个与 cout.setf(ios::fixed) 有关的奇怪问题。我花了很长时间才找到原因,并想在这里询问以了解更多信息。
问题是这样的 - 使用 cout.setf(ios::fixed) 时,所有浮点数都被打印为十六进制数字。为什么会出现这种情况? 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;
}
Output
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
See the live sample here
请注意,当我进行更改时,问题就会消失
cout.setf(ios::fixed);
to
cout.setf(ios::fixed, ios::floatfield);
因为你告诉它。
From setfcppreference.com 上的文档:
科学的- 使用科学记数法或十六进制记数法(如果与固定结合)生成浮点类型:请参阅std::scientific
fixed- 使用固定表示法或十六进制表示法(如果与科学结合)生成浮点类型:请参阅std::fixed
所以,设置时std::fixed
,你需要取消设置std::scientific
(这就是你揭露的std::floatfield
确实如此,因为std::floatfield
is std::scientific|std::fixed|(std::scientific|std::fixed)|0
) 以避免使用十六进制表示法。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)