Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> C++

ฟังก์ชัน rint(), rintf(), rintl() ใน C++: ปัดเศษ Floating-Point ตาม Rounding Mode

ฟังก์ชัน rint ฟамиลี (rint, rintf, rintl) ใน Header <cmath> ใช้สำหรับปัดเศษ Floating-Point ให้เป็นจำนวนเต็ม (คืนค่าเป็น Floating-Point Type เดียวกัน) ตาม Current Rounding Mode ที่ตั้งค่าผ่าน fesetround() (Header <cfenv>)

ลายเซ็นฟังก์ชัน

float       rintf(float arg);       // C++11
double      rint(double arg);       // C++11
long double rintl(long double arg); // C++11
// Overloads สำหรับ Integral Types (แปลงเป็น double ก่อน)

Rounding Modes (จาก <cfenv>)

Macroพฤติกรรม
FE_TONEARESTปัดไปค่าที่ใกล้ที่สุด (คู่ถ้ากึ่งกลาง) - Default
FE_UPWARDปัดขึ้น (Ceiling)
FE_DOWNWARDปัดลง (Floor)
FE_TOWARDZEROปัดเข้าสู่ศูนย์ (Truncate)

ตัวอย่าง: ระบุ Rounding Mode ด้วย fesetround()

#include <iostream>
#include <cmath>
#include <cfenv>

using namespace std;

int main() {
    double x = 53.26;
    double y = 53.86;

    // Default: FE_TONEAREST
    cout << "Default (Nearest): rint(" << x << ") = " << rint(x) 
         << ", rint(" << y << ") = " << rint(y) << endl;
    // 53, 54

    // ปัดขึ้น
    fesetround(FE_UPWARD);
    cout << "FE_UPWARD: rint(" << x << ") = " << rint(x) 
         << ", rint(" << y << ") = " << rint(y) << endl;
    // 54, 54

    // ปัดลง
    fesetround(FE_DOWNWARD);
    cout << "FE_DOWNWARD: rint(" << x << ") = " << rint(x) 
         << ", rint(" << y << ") = " << rint(y) << endl;
    // 53, 53

    // ปัดเข้าสู่ศูนย์
    fesetround(FE_TOWARDZERO);
    cout << "FE_TOWARDZERO: rint(" << x << ") = " << rint(x) 
         << ", rint(" << y << ") = " << rint(y) << endl;
    // 53, 53

    return 0;
}

ความแตกต่างกับ ฟังก์ชันปัดเศษอื่นๆ

Functionคืนค่าRounding Modeหมายเหตุ
rintFloating-Pointตาม fesetroundไม่ยก FE_INEXACT Exception
nearbyintFloating-Pointตาม fesetroundไม่ยก FE_INEXACT (เหมือน rint)
roundFloating-PointHalf Away from Zeroคงที่ ไม่ขึ้นกับ Mode
lrint / llrintlong / long longตาม fesetroundคืน Integer Type
lround / llroundlong / long longHalf Away from Zeroคืน Integer Type

กรณีพิเศษ

  • Input เป็น NaN → คืน NaN
  • Input เป็น ±Infinity → คืน ±Infinity
  • Input เป็น ±0 → คืน ±0
  • ผลลัพธ์เกิน Range ของ Return Type → เกิด Domain Error (Implementation-defined)

สรุป

rint เหมาะสำหรับการคำนวณทางวิทยาศาสตร์/การเงินที่ต้องควบคุม Rounding Mode อย่างชัดเจน (เช่น Accounting ใช้ FE_TONEAREST หรือ FE_TOWARDZERO) ต่างจาก round() ที่ Hard-code Mode ไว้แล้ว