美文网首页
c++中正确使用round()来四舍五入计算

c++中正确使用round()来四舍五入计算

作者: 路长心自远 | 来源:发表于2023-06-04 14:40 被阅读0次

    说明

    四舍五入的函数参数可以有多种数据类型。不同的数据类型有不同的结果。
    当他的参数应该是浮点数的时候,结果才是真正的四舍五入。

    例子

    /*
    g++ -g -std=c++17 ./src/basic_demo.cpp -o basic_demo
    */
    
    #include <iostream>
    #include <cmath>
    
    void test_round(){
        // 参数是浮点数的情况,结果正确
        std::cout << "std::round(12.369)\t" << std::round(12.369) << std::endl;
        std::cout << "std::round(12.9)\t" << std::round(12.9) << std::endl;
    
        int a1 = 10;
        int a2=13;
        int b=7;
    
        //参数是整数组成的分子和分母的时候,结果错误
        std::cout << "std::round(10/7)\t" << std::round(10/7) << std::endl;
        std::cout << "std::round(13/7)\t" << std::round(13/7) << std::endl;
    
        //调整一下参数的类型,结果正确
        std::cout << "std::round(1.0*10/7)\t" << std::round((1.0*10)/7) << std::endl;
        std::cout << "std::round(1.0*13/7)\t" << std::round((1.0*13)/7) << std::endl;
    }
    
    
    int main(int argc, char **argv)
    {
        test_round();
        return 0;
    }
    

    程序的结果

    baby@ubuntu2204:~/devel/cpp$ ./basic_demo 
    std::round(12.369)      12
    std::round(12.9)        13
    std::round(10/7)        1
    std::round(13/7)        1
    std::round(1.0*10/7)    1
    std::round(1.0*13/7)    2
    

    相关文章

      网友评论

          本文标题:c++中正确使用round()来四舍五入计算

          本文链接:https://www.haomeiwen.com/subject/fcmbedtx.html