在这里,我们将看到C ++中的fesetround()andfegetround()方法。这些方法可以在cfenv库中找到。
该fesetround()方法用于将指定的浮点取整方向设置为当前取整方向。这被用来与rint(),nearbyint()和在C ++中一些其它的舍入函数。
语法如下-
int fesetround(int 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()方法用于获取与当前舍入方向相对应的浮点舍入宏。此功能用于与rint(),nearbyint()和在C ++中一些其它的舍入方法。
语法如下-
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