跳到主要内容

C++ round() 四舍五入函数

C++ 中的 round() 函数返回最接近参数的整数值,半数情况从零开始舍入。

它定义在 cmath 头文件中。

示例

#include <iostream>
#include <cmath>
using namespace std;

int main() {

// 显示最接近 15.5 的整数值
cout << round(15.5);

return 0;
}

// 输出:16

round() 语法

round() 函数的语法为:

round(double num);

round() 参数

round() 函数接受以下参数:

  • num - 需要四舍五入的浮点数。它可以是以下类型之一:
    • double
    • float
    • long double

round() 返回值

round() 函数返回:

  • 最接近 num 的整数值,半数情况从零开始舍入。

round() 原型

cmath 头文件中定义的 round() 函数原型为:

double round(double num);

float round(float num);

long double round(long double num);

// 对于整数类型
double round(T num);

示例 1:C++ round()

#include <iostream>
#include <cmath>
using namespace std;

int main() {

double num, result;

num = 11.16;
result = round(num);

cout << "round(" << num << ") = " << result << endl;

num = 13.87;
result = round(num);

cout << "round(" << num << ") = " << result << endl;

num = 50.5;
result = round(num);

cout << "round(" << num << ") = " << result;

return 0;
}

输出

round(11.16) = 11
round(13.87) = 14
round(50.5) = 51

示例 2:C++ round() 处理负数

#include <iostream>
#include <cmath>
using namespace std;

int main() {

double num, result;

num = -11.16;
result = round(num);

cout << "round(" << num << ") = " << result << endl;

num = -13.87;
result = round(num);

cout << "round(" << num << ") = " << result << endl;

num = -50.5;
result = round(num);

cout << "round(" << num << ") = " << result;

return 0;
}

输出

round(-11.16) = -11
round(-13.87) = -14
round(-50.5) = -51

示例 3:C++ round() 对整数类型

#include <iostream>
#include <cmath>
using namespace std;

int main() {
double result;

int num = 15;
result = round(num);

cout << "round(" << num << ") = " << result;

return 0;
}

输出

round(15) = 15

对于整数值,使用 round() 函数返回的值与输入相同。因此,实际上不常用于处理整数值。