C++ 中的 round()
函数返回最接近参数的整数值,其中半数情况(即小数部分为 0.5)将朝远离零的方向取整。
它定义在 cmath 头文件中。
示例
#include <iostream>
#include <cmath>
using namespace std;
int main() {
// display integral value closest to 15.5
cout << round(15.5);
return 0;
}
// Output: 16
round() 语法
round()
函数的语法是
round(double num);
round() 参数
round()
函数接受以下参数
- num - 一个要进行四舍五入的浮点数。它可以是以下类型
双精度浮点数
浮点数
long double
round() 返回值
round()
函数返回
- 最接近 num 的整数值,其中半数情况(即小数部分为 0.5)将朝远离零的方向取整。
round() 原型
round()
函数在 cmath 头文件中定义的原型如下:
double round(double num);
float round(float num);
long double round(long double num);
// for integral type
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()
函数会返回与输入相同的值。因此,在实践中它通常不用于整数值。
另请阅读