【问题标题】:Can I set a variable that will change the floatfield when using cout?使用 cout 时,我可以设置一个变量来改变浮点域吗?
【发布时间】:2020-01-07 14:55:02
【问题描述】:

我希望能够根据条件轻松地将 floatfield 从科学更改为固定,因此我的结果将从 3.000000e+00 更改为 3.0,使用的代码可能如下所示:

some_datatype floatfield;
float number = 5.894
if (condition) {
    floatfield = 'scientific';
} else floatfield = 'fixed';
cout << "hello" << floatfield << number << endl;

我知道我可以使用

float number = 5.894
if (condition) {
    cout << "hello" << scientific << number << endl;
} else cout << "hello" << fixed << number << endl;

但是如果我开始使用更多的流格式标志,这并不能很好地概括。

如果some_datatype 存在,它是什么?如果没有,还有其他方法可以使用条件更改流格式标志吗?

【问题讨论】:

  • 第一个(众多)问题 - some_datatype 是什么?
  • 这是问题的一部分——如果它存在的话,我不知道它会是什么。已编辑问题以包含此
  • some_datatype (std::ios_base::fmtflags) 将是 implementation specific。我不明白你在写cout &lt;&lt; floatfield 时会看到什么,如果可能的话,这将打印floatfield 的值,而不是以任何方式调整 cout 格式......
  • 这有什么不清楚的地方?来吧伙计们。
  • Here's the answer. 如果问题没有被关闭,本来会这样发布的。 :( 如果它重新打开,请联系我,我会修复它

标签: c++ cout scientific-notation iomanip


【解决方案1】:

I/O 操纵器实际上是函数 (!),而您要在它们之间切换的操纵器恰好具有相同的签名。

因此,您可以使用函数指针来实现您的目标:

#include <iomanip>
#include <iostream>

int main()
{
    using ManipFuncType = std::ios_base&(std::ios_base&);
    const bool condition = true; // or false!

    ManipFuncType* floatfield;
    float number = 5.894;
    if (condition)
        floatfield = std::scientific;
    else
        floatfield = std::fixed;

    std::cout << "hello" << floatfield << number << std::endl;
}

(live demo)

【讨论】:

    【解决方案2】:

    我不确定我是否正确理解了这个问题,但这可能是一个解决方案:

    #include <iostream>
    using namespace std;
    
    struct my_float {
        float value_;
        bool scientific_ = true;
        my_float(float value) : value_(value) {}
        void set_scientific() { scientific_ = true; }
        void set_fixed() { scientific_ = false; }
    };
    ostream& operator<<(ostream& os, const my_float& f) {
        if (f.scientific_)
            return os << scientific << f.value_;
        else
            return os << fixed << f.value_;
    }
    
    int main() {
        my_float number = 5.894;
        bool condition = true; // <--- Change this!
        if (condition) {
            number.set_scientific();
        }
        else {
            number.set_fixed();
        }
        cout << "hello" << number << endl;
    
        return 0;
    }
    

    这当然是很粗略的,当然这门课还可以更全。

    不要使用它来存储许多浮点数,因为 id 可能很容易使您的内存需求翻倍。

    【讨论】:

    • 谢谢,这很有帮助。 @LightnessRacesinOrbit 在对该问题的评论中发布了一个更好的答案 - 这就是我想要的!
    猜你喜欢
    • 2010-09-08
    • 2019-11-07
    • 1970-01-01
    • 2015-07-20
    • 2020-03-17
    • 2014-07-14
    • 1970-01-01
    • 2022-12-17
    • 2013-01-01
    相关资源
    最近更新 更多