在 C++ 中,可以使用库函数 'round()' 来进行四舍五入。'round()' 函数的原型如下:

double round(double x);

该函数接受一个 'double' 类型的参数 x,并返回一个最接近 x 的整数值,四舍五入到最近的整数。需要注意的是,函数 'round()' 返回的是 'double' 类型的结果。

以下是一个简单的示例代码,演示如何使用 'round()' 函数进行四舍五入:

#include <iostream>
#include <cmath>

int main() {
    double number = 3.6;

    double roundedNumber = round(number);

    std::cout << '原始数字: ' << number << std::endl;
    std::cout << '四舍五入后的数字: ' << roundedNumber << std::endl;

    return 0;
}

输出结果:

原始数字: 3.6
四舍五入后的数字: 4

通过 'round()' 函数,你可以将一个浮点数四舍五入到最近的整数值。如果需要将其它类型的变量进行四舍五入,你可以先将其转换为 'double' 类型,然后再应用 'round()' 函数进行处理。

C++ 四舍五入:使用 round() 函数

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

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