• 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. }

     运行结果

  • 相关阅读:
    系统升级丨酷雷曼6大功能,轻松玩转全景营销
    PPLiteSeg实时语义分割预测结果输出控制无人车转向角度方向实现沿车道无人驾驶
    SpringSecurity简明教程
    【PyTorch】PyTorch基础知识——自动求导
    JS中的闭包
    10G SFP+线缆选购指南
    PAT 1028 List Sorting
    项目验收报告 和 项目总结
    Java高并发编程实战1,那些年学过的锁
    学习css动画-animation
  • 原文地址:https://blog.csdn.net/Gary_ghw/article/details/125498414