【问题标题】:Print one (float) decimal using cout使用 cout 打印一个(浮点)小数
【发布时间】:2012-11-17 21:39:05
【问题描述】:

我有一个浮点数,我想在小数点后打印一位。我怎样才能使用cout 做到这一点?我尝试了以下代码,但显示错误。

#include <iostream>

using namespace std;

int main()
{
    float time = 2.2;
    cout.precision(1);
    cout << time << endl;

    return 0;
}

【问题讨论】:

    标签: c++ floating-point iostream css-position cout


    【解决方案1】:

    您需要将 tge 精度设置为 1,并将格式化标志浮动到 fixed

    std::cout << std::fixed << std::setprecision(1);
    

    顺便说一句,不要使用std::endl。要获得换行符,请使用 '\n',如果您真的要刷新流,请使用 std::flush

    【讨论】:

    • 似乎需要一个指向 Scott Meyers 的 The little endl that couldn't (PDF) 的链接 :)
    • 好吧,如果我要链接一篇文章,我当然会链接this 一个!我真的不知道斯科特的文章......
    • 我真的不知道你的 :) 谢谢你的链接
    • @sehe:我应该向 Scott 提及 std::unitbuf 操纵器:这就是 std::cerr 获得无缓冲而不是使用 setbuf(0, 0) 的方式。
    • @DietmarKühl:是的。并修复 Meyers 文章中的过时信息:unitbuf 在其他流上默认为 0,std::cout 默认(允许)缓冲。
    猜你喜欢
    • 1970-01-01
    • 2022-09-11
    • 2017-06-02
    • 1970-01-01
    • 1970-01-01
    • 2014-12-28
    • 2011-08-19
    • 1970-01-01
    相关资源
    最近更新 更多