C ++精度 - setprecision的行为

时间:2013-09-02 06:59:19

标签: c++ floating-point precision floating-point-precision double-precision

据我所知,setprecision函数指定最小精度但是当我运行以下代码时,我只得到小数点后面的3个数字:

int main()
{
    double a = 123.4567890;
    double b = 123.4000000;
    std::cout << std::setprecision(5) << a << std::endl; // Udesireble 
    std::cout.setf(std::ios::fixed);
    std::cout << std::setprecision(5) << a << std::endl; // Desireble 

    std::cout << std::setprecision(5) << b << std::endl; // Udesireble
    std::cout.unsetf(std::ios::fixed);
    std::cout << std::setprecision(5) << b << std::endl; // Desireble 
    return 0;
}

打印:

123.46      // Udesireble
123.45679   // Desireble 
123.40000   // Udesireble
123.4       // Desireble

有什么方法可以避免自己检查小数点后面的位数,以便知道是否设置固定?

2 个答案:

答案 0 :(得分:1)

我的印象是您需要首先格式化为string,然后用空格替换尾随零。

答案 1 :(得分:0)

对于流,您可以使用两个功能。 setfill(char_type c),用于设置要写入的字符,以匹配所需字符的数量(更多信息here

有setw(int)函数,它设置要显示的值的字段宽度。 (文件here

使用这些功能,您可能有一个解决方案

相关问题