여기서 우리는 C++의 fesetround() 및 fegetround() 메서드를 볼 것입니다. 이러한 메소드는 cfenv 라이브러리에서 찾을 수 있습니다.
fesetround() 메서드는 지정된 부동 소수점 반올림 방향을 현재 반올림 방향으로 설정하는 데 사용됩니다. 이것은 rint(), Nearlyint() 및 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(), Nearlyint() 및 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