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

remainder() ใน C++: หาเศษจากการหารแบบ Round to Nearest

remainder() คืออะไร?

remainder() ใน <cmath> คำนวณเศษจากการหาร numerator / denominator โดย **ปัด quotient ให้ใกล้ค่าคู่ที่สุด (round to nearest, ties to even)**

ต่างจาก fmod() ที่ปัด quotient ไปทางศูนย์ (truncate toward zero)

สูตร

remainder = numerator - round_quotient × denominator

โดย round_quotient = round(numerator / denominator) (round to nearest, ties to even)

Syntax

double remainder(double x, double y);
float remainderf(float x, float y);
long double remainderl(long double x, long double y);

ตัวอย่าง

#include <cmath>
#include <iostream>
using namespace std;

int main() {
    cout << "remainder(51, 5) = " << remainder(51, 5) << "\n";   // 1  (51/5=10.2→10, 51-10*5=1)
    cout << "remainder(53, 5) = " << remainder(53, 5) << "\n";   // -2 (53/5=10.6→11, 53-11*5=-2)
    cout << "remainder(52, 5) = " << remainder(52, 5) << "\n";   // 2  (52/5=10.4→10, 52-10*5=2)
    cout << "remainder(52.5, 5) = " << remainder(52.5, 5) << "\n"; // 2.5 (10.5→10 ties to even)
    
    // เปรียบเทียบกับ fmod
    cout << "fmod(53, 5) = " << fmod(53, 5) << "\n";           // 3  (truncate 10.6→10)
    cout << "fmod(-53, 5) = " << fmod(-53, 5) << "\n";         // -3
    cout << "remainder(-53, 5) = " << remainder(-53, 5) << "\n"; // 2  (-10.6→-11, -53-(-11)*5=2)
    
    // Denominator = 0
    cout << "remainder(51, 0) = " << remainder(51, 0) << "\n"; // NaN / domain error
    
    return 0;
}

Output

remainder(51, 5) = 1
remainder(53, 5) = -2
remainder(52, 5) = 2
remainder(52.5, 5) = 2.5
fmod(53, 5) = 3
fmod(-53, 5) = -3
remainder(-53, 5) = 2
remainder(51, 0) = -nan

ความต่าง remainder vs fmod

คุณสมบัติremainder()fmod()
Quotient roundingRound to nearest (ties to even)Truncate toward zero
Result signอาจต่างจาก numeratorเหมือน numerator เสมอ
Range|result| ≤ |denom|/2|result| < |denom|
IEEE 754CompliantNot compliant

เมื่อไหร่ควรใช้ remainder()?

  • ต้องการ IEEE 754 compliant remainder
  • งานคณิตศาสตร์/วิศวกรรมที่ต้องการ rounding ให้สมดุล
  • Argument reduction ในการคำนวณ transcendental functions

สรุป

remainder(x, y) คืนเศษจากการหารที่ปัด quotient ให้ใกล้ค่าคู่ที่สุด ให้ผลลัพธ์ที่ "สมดุล" กว่า fmod() เหมาะสำหรับงานคำนวณทางวิทยาศาสตร์