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

     运行结果

  • 相关阅读:
    源码分析之上下文构建
    ARFoundation系列讲解 - 78 AR室内导航三
    从数字化过渡到智能制造
    详解java重定向和转发的区别
    Windows 内网渗透之横向渗透
    git-命令行显示当前目录分支
    FPGA之旅设计99例之第九例-----驱动0.96寸OLED屏
    Java:为什么使用Java开发Web和移动应用
    AOP中的一些重要术语简介
    CURL
  • 原文地址:https://blog.csdn.net/Gary_ghw/article/details/125498414