ที่นี่เราจะเห็นวิธี fesetround() และ fegetround() ใน C++ วิธีการเหล่านี้สามารถพบได้ในไลบรารี 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