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

     运行结果

  • 相关阅读:
    【存储数据恢复】NetApp存储误删文件夹的数据恢复案例
    VUE使用DXFParser组件解析dxf文件生成图片
    网络工程师的爬虫技术之路:跨界电商与游戏领域的探索
    socket.error: [Errno 10049]错误
    关于electron打包卡在winCodeSign下载问题
    Java应用层数据链路追踪(附优雅打印日志姿势)
    UDS应用场景
    uniapp canvas 无法获取 webgl context 的问题解决
    HTML进阶(5)- 其他元素
    RunnerGo UI自动化使用流程
  • 原文地址:https://blog.csdn.net/Gary_ghw/article/details/125498414