如何指定精度舍入 [英] How to specify setprecision rounding

查看:95
本文介绍了如何指定精度舍入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当流到std输出时,我是否可以指定setprecision以舍入双精度值?

Can I specify setprecision to round double values when stream to std output?

ofile << std::setprecision(12) << total_run_time/TIME << "\n";

输出:
0.756247615801

Output: 0.756247615801

ofile << std::setprecision(6)<< total_run_time/TIME << "\n";

输出:
0.756248

Output: 0.756248

但我需要输出 0.756247

感谢

推荐答案

< cfenv>还有 std :: fesetround ,它设置舍入方向:

There is also std::fesetround from <cfenv>, which sets the rounding direction:

#include <iostream>
#include <iomanip>
#include <cmath>
#include <cfenv>

int main () {
    double runtime = 0.756247615801;

    // Set rounding direction and output with some precision:
    const auto prev_round = std::fegetround();
    std::fesetround(FE_DOWNWARD);    
    std::cout << "desired: " << std::setprecision(6) << runtime << "\n";

    // Restore previous rounding direction and output for testing:
    std::fesetround(prev_round);
    std::cout << "default: " << std::setprecision(6) << runtime << "\n";
}

(请注意,这些不是我推荐的评论,他们只是为了辅导目的)

输出:

desired: 0.756247
default: 0.756248

/ strong>我没有在标准中找到任何提及,运算符<< 浮动类型的重载来遵守舍入方向。

Important note, though: I did not find any mention in the standard, that the operator<< overloads for floating types have to honour the rounding direction.

这篇关于如何指定精度舍入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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