C++ 中的 Fesetround() 和 fegetround()
本文将介绍 C++ 中的 fesetround() 和 fegetround() 方法。这些方法可以在 cfenv 库中找到。
fesetround() 方法用于将指定的浮点数舍入方向设为当前舍入方向。它与 C++ 中的 rint()、nearbyint() 以及其他一些舍入函数结合使用。
如下是语法 −
int fesetround(int round);
round 可以是 FE_TONEAREST、FE_DOWNWARD、FE_UPWARD 等。当舍入方向成功应用于所需的方式时,此函数返回 0。
示例
#include <cfenv >
#include <cmath>
#include <iostream>
using namespace std;
main() {
double x = 4.7, ans;
fesetround(FE_TONEAREST); //round to nearest integer
ans = rint(x);
cout << "Nearest Integer is: " << ans << endl;
fesetround(FE_TOWARDZERO); //rounding towards zero
ans = rint(x);
cout << "Rounding towards 0, value is: " << ans << endl;
fesetround(FE_DOWNWARD); //rounding to downwards
ans = rint(x);
cout << "Nearest Integer below the number: " << ans << endl;
fesetround(FE_UPWARD); //rounding to upwards
ans = rint(x);
cout << "Nearest Integer above the number: " << ans << endl;
}输出
Nearest Integer is: 5 Rounding towards 0, value is: 4 Nearest Integer below the number: 4 Nearest Integer above the number: 5
现在让我们了解一下 fegetround() 方法,该方法用于获取与当前舍入方向对应的浮点数舍入宏。此函数与 C++ 中的 rint()、nearbyint() 以及其他一些舍入方法结合使用。
如下是语法 −
int fegetround();
它返回与浮点数舍入宏对应的数字。
- FE_DOWNWARD
- FE_TONEAREST
- FE_TOWARDZERO
- FE_UPWARD
示例
#include <cfenv >
#include <cmath>
#include <iostream>
using namespace std;
void float_direction() {
switch (fegetround()) {
case FE_TONEAREST:
cout << "Macro is: FE_TONEAREST";
break;
case FE_DOWNWARD:
cout << "Macro is: FE_DOWNWARD";
break;
case FE_UPWARD:
cout << "Macro is: FE_UPWARD";
break;
case FE_TOWARDZERO:
cout << "Macro is: FE_TOWARDZERO";
break;
default:
cout << "unknown";
};
cout << endl;
}
main() {
double x = 4.7, ans;
fesetround(FE_TONEAREST); //round to nearest integer
ans = rint(x);
cout << "Nearest Integer is: " << ans << endl;
float_direction();
fesetround(FE_TOWARDZERO); //rounding towards zero
ans = rint(x);
cout << "Rounding towards 0, value is: " << ans << endl;
float_direction();
fesetround(FE_DOWNWARD); //rounding to downwards
ans = rint(x);
cout << "Nearest Integer below the number: " << ans << endl;
float_direction();
fesetround(FE_UPWARD); //rounding to upwards
ans = rint(x);
cout << "Nearest Integer above the number: " << ans << endl;
float_direction();
}输出
Nearest Integer is: 5 Macro is: FE_TONEAREST Rounding towards 0, value is: 4 Macro is: FE_TOWARDZERO Nearest Integer below the number: 4 Macro is: FE_DOWNWARD Nearest Integer above the number: 5 Macro is: FE_UPWARD
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP