Rint()、rintf()、rintl() 在 C++ 中


这里我们将介绍三个函数。这三个函数是 Rint()、rintf() 和 rint()。这些函数用于将浮点数转换为四舍五入的格式。

rint() 函数

此函数用于将浮点数四舍五入为整数。语法如下。如果结果超出返回类型,则可能会发生域错误。当参数为 0 或无穷大时,它将返回未修改的值

float rint(float argument)
double rint(double argument)
long double rint(long double argument)

示例

#include <cmath>
#include <iostream>
using namespace std;
main() {
   double a, b, x, y;
   x = 53.26;
   y = 53.86;
   a = rint(x);
   b = rint(y);
   cout << "The value of a: " << a << endl;
   cout << "The value of b: " << b;
}

输出

The value of a: 53
The value of b: 54

rintf() 函数

此函数与 rint 相同,但唯一的区别是这里所有参数和返回类型都是 float 类型。在此示例中,我们将使用 fesetround() 方法来指定四舍五入类型。

float rintf(float argument)

示例

#include <cmath>
#include <fenv.h>
#include <iostream>
using namespace std;
main() {
   double a, b, x, y;
   x = 53.26;
   y = 53.86;
   fesetround(FE_UPWARD);
   a = rintf(x);
   fesetround(FE_DOWNWARD);
   b = rintf(y);
   cout << "The value of a: " << a << endl;
   cout << "The value of b: " << b;
}

输出

The value of a: 54
The value of b: 53

rintl() 函数

此函数与 rint 相同,但唯一的区别是这里所有参数和返回类型都是 long double 类型。在此示例中,我们将使用 fesetround() 方法来指定四舍五入类型。

long double rintl(long double argument)

示例

#include <cmath>
#include <fenv.h>
#include <iostream>
using namespace std;
main() {
   double a, b, x, y;
   x = 53547.55555555555;
   y = 53547.55555555523;
   fesetround(FE_UPWARD);
   a = rintl(x);
   fesetround(FE_DOWNWARD);
   b = rintl(y);
   cout << "The value of a: " << a << endl;
   cout << "The value of b: " << b;
}

输出

The value of a: 53548
The value of b: 53547

更新日期:30-07-2019

116 次浏览

事业起航

完成课程,获得认证

开始学习
广告
© . All rights reserved.