• C++保留小数点后两位(floor&ceil&round)详解


     C++四舍五入保留小数点后两位

     示例

    1. #include <iostream>
    2. using namespace std;
    3. int main()
    4. {
    5. double i = 2.235687;
    6. double j = round(i * 100) / 100;
    7. cout << "The original number is " << i << endl;
    8. cout << "The keep two decimal of 2.235687 is " << j << endl;
    9. system("pause");
    10. return 0;
    11. }

     运行结果

    函数解析见下面


     1、floor函数

    功能:把一个小数向下取整
          即就是如果数是2.2,那向下取整的结果就为2.000000
    原型:double floor(doube x);
        参数解释:
            x:是需要计算的数

    示例

    1. #include <iostream>
    2. using namespace std;
    3. int main()
    4. {
    5. double i = floor(2.2);
    6. double j = floor(-2.2);
    7. cout << "The floor of 2.2 is " << i << endl;
    8. cout << "The floor of -2.2 is " << j << endl;
    9. system("pause");
    10. return 0;
    11. }

    运行结果

    2、ceil函数

    功能:把一个小数向上取整
          即就是如果数是2.2,那向下取整的结果就为3.000000
    原型:double ceil(doube x);
        参数解释:
            x:是需要计算的数

    示例

    1. #include <iostream>
    2. using namespace std;
    3. int main()
    4. {
    5. double i = ceil(2.2);
    6. double j = ceil(-2.2);
    7. cout << "The ceil of 2.2 is " << i << endl;
    8. cout << "The ceil of -2.2 is " << j << endl;
    9. system("pause");
    10. return 0;
    11. }

     运行结果

    3、round函数

    功能:把一个小数四舍五入
          即就是如果数是2.2,那向下取整的结果就为2
                     如果数是2.5,那向上取整的结果就为3
    原型:double round(doube x);
        参数解释:
            x:是需要计算的数

     示例

    1. #include <iostream>
    2. using namespace std;
    3. int main()
    4. {
    5. double i = round(2.2);
    6. double x = round(2.7);
    7. double j = round(-2.2);
    8. double y = round(-2.7);
    9. cout << "The round of 2.2 is " << i << endl;
    10. cout << "The round of 2.7 is " << x << endl;
    11. cout << "The round of -2.2 is " << j << endl;
    12. cout << "The round of -2.7 is " << y << endl;
    13. system("pause");
    14. return 0;
    15. }

     运行结果

  • 相关阅读:
    精简代码 减少冗余
    ETCD数据库源码分析——rawnode简单封装
    Allegro基本规则设置指导书
    【命令式编程和声明式编程】
    滑动窗口算法
    BHQ-2 NHS,916753-62-3作为各种荧光共振能量转移DNA检测探针中淬灭部分
    NginxWebUI runCmd 远程命令执行漏洞复现 [附POC]
    (2023|ICLR,检索引导,交叉引导,EntityDrawBench)Re-Imagen:检索增强的文本到图像生成器
    csv和excel文件操作
    在 Visual Studio 2022 中配置 OpenCV
  • 原文地址:https://blog.csdn.net/Gary_ghw/article/details/125498414