温馨提示×

c++四舍五入保留两位小数怎么实现

c++
小亿
244
2024-02-01 10:16:33
栏目: 编程语言

在C++中,可以使用以下方法来实现四舍五入并保留两位小数:

  1. 使用<iomanip>库中的setprecision()函数来设置小数精度。

    #include <iostream>
    #include <iomanip>
    
    int main() {
        double num = 3.14159;
        std::cout << std::fixed << std::setprecision(2) << num << std::endl;
        return 0;
    }
    

    输出结果为:3.14

  2. 使用round()函数四舍五入,并将结果转换为保留两位小数的字符串。

    #include <iostream>
    #include <cmath>
    #include <string>
    #include <sstream>
    
    std::string roundToTwoDecimalPlaces(double num) {
        double rounded = round(num * 100) / 100;
        std::ostringstream ss;
        ss << std::fixed << std::setprecision(2) << rounded;
        return ss.str();
    }
    
    int main() {
        double num = 3.14159;
        std::cout << roundToTwoDecimalPlaces(num) << std::endl;
        return 0;
    }
    

    输出结果为:3.14

注意:以上两种方法都是将结果输出为字符串形式,如果需要保留两位小数的浮点数,可以将结果转换为double类型。

0