为什么cout.setf(ios :: fixed)将我的浮点数更改为十六进制? [英] Why does cout.setf(ios::fixed) change my floats to hexadecimal?

查看:254
本文介绍了为什么cout.setf(ios :: fixed)将我的浮点数更改为十六进制?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我最近遇到了一个与cout.setf(ios :: fixed)有关的怪异问题。我花了相当长的时间来查找原因,以为我想在这里了解更多。

I experienced this weird issue recently having to do with cout.setf(ios::fixed). Took me quite a while to track down the cause and thought I'd ask here to learn more.

问题是这样的-所有浮点数都打印为十六进制数使用cout.setf(ios :: fixed)时。为什么会这样? ios :: base的文档似乎并不暗示这种情况会发生(至少对我而言)。我正在使用g ++ 5.3.0,下面粘贴是一个最小的示例和输出。

The issue is this - all floating point numbers were printed as hexadecimal numbers when using cout.setf(ios::fixed). Why does this happen? The documentation of ios::base doesn't seem to imply that this will happen (at least to me). I am using g++ 5.3.0 and pasted below is a minimal example and the output.

   #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

在此处查看实时示例

请注意,问题已解决当我更改

Note that the issue goes away when I change

 cout.setf(ios::fixed);

 cout.setf(ios::fixed, ios::floatfield);


推荐答案

因为您告诉过它。

来自 setf cppreference.com上的文档

From setf documentation on cppreference.com:


科学-生成浮点类型使用科学计数法或十六进制计数法(如果与固定值结合使用):请参见 std :: scientific

固定-生成浮点类型使用固定记法,或者十六进制记法(如果与科学结合使用):请参见 std :: fixed

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 :: floatfield std :: scientific | std :: fixed |(std :: scientific | std :: fixed)| 0 )避免使用十六进制表示法。

So, when setting std::fixed, you need to unset std::scientific (which is what your unmasking of std::floatfield does, because std::floatfield is std::scientific|std::fixed|(std::scientific|std::fixed)|0) to avoid the hex notation.

这篇关于为什么cout.setf(ios :: fixed)将我的浮点数更改为十六进制?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆