可以使用以下代码来使用 round() 函数保留一位小数:

#include <iostream>
#include <cmath>

int main() {

    double num = 3.14159;

    double rounded_num = round(num * 10) / 10.0;

    std::cout << "Original number: " << num << std::endl;
    std::cout << "Rounded number: " << rounded_num << std::endl;

    return 0;
}

输出:

Original number: 3.14159
Rounded number: 3.1

在这个例子中,我们将原始数字乘以10,这样就可以将小数点向右移动一位,然后使用 round() 函数将其四舍五入到最接近的整数。最后,我们将结果除以10.0,这样就可以将小数点向左移动一位,得到一个保留一位小数的数字。

c++ round 想要保留一位小数

原文地址: https://www.cveoy.top/t/topic/e1W3 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录