zoukankan      html  css  js  c++  java
  • C++ 11保留小数点的四舍五入方案

    当然,C++ 11提供各类型的std::round来四舍五入,但是没有一个能直接支持保留小数点位数的四舍五入方案。

    所以需要通过setprecision来实现:

    1 #include <iomanip>
    2 #include <iostream>
    3 std::cout << std::fixed << setprecision(5) << 5.324356;

    以上就是保留5位小数并四舍五入,如果把std::fixed去掉,那么就是保留5位有效位数并四舍五入。如果觉得标准输出流处理不方便,可以用封装stringstream类来实现字符串的转换的四舍五入函数:

     1 #include <iomanip>
     2 #include <sstream>
     3 #include <iostream>
     4 
     5 static std::string roundAny(double r,int precision){
     6     std::stringstream buffer;
     7     buffer << std::fixed << setprecision(precision) << r;
     8     return buffer.str();
     9 }
    10 
    11 int main()
    12 {
    13    std::cout << roundAny(45.65658866,5) << std::endl; // C++11
    14     std::cout << roundAny(21.6463,3)  << std::endl; // C++11
    15    return 0;
    16 }
  • 相关阅读:
    上下界网络流——概念解析与快速入门(待修改)
    maomao的现在与未来
    exgcd证明和最基础应用
    快速入门Splay
    luogu 2515
    bzoj 1996
    *51nod 1409
    51nod 1412
    51nod 1503
    51nod 1020
  • 原文地址:https://www.cnblogs.com/foohack/p/7337807.html
Copyright © 2011-2022 走看看