c++ - 为什么 cout.setf(ios::fixed) 将我的 float 更改为十六进制?

标签 c++ cout

我最近遇到了这个与 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

See the live sample here

请注意,当我更改后问题就消失了

 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: see std::fixed

所以,当设置std::fixed , 你需要取消设置 std::scientific (这是你对 std::floatfield 的揭露,因为 std::floatfieldstd::scientific|std::fixed|(std::scientific|std::fixed)|0 )以避免十六进制表示法。

关于c++ - 为什么 cout.setf(ios::fixed) 将我的 float 更改为十六进制?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36362077/

相关文章:

c++ - Cout 不打印号码

c++ - C++ atexit() 函数发生奇怪的崩溃

c++ - 在 C++ 中使用 fread 时实现固定大小缓冲区的最佳方法是什么?

c++ - winsock2:recvfrom() 函数以错误 10022(无效参数)结束

c++ - 为什么std::cout无法为我的int8_t数字输出正确的值?

c++ - cout 总是将我的 double 打印为 0

C++函数cout重定向到文件

c++ - 运行 SDL2 时 Xcode 崩溃

c++ - 类继承 C++

c++ - 警告 C4244 : 'argument' : conversion from 'SIZE_T' to 'DWORD' , 可能丢失数据