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

ฟังก์ชัน remainder() ใน C++: หาเศษจุดทศนิยม

remainder(x, y) ใน <cmath> คำนวณเศษของ x/y แบบ Floating Point

นิยาม

remainder(x, y) = x - n × y

โดย n = ค่าจำนวนเต็มที่ใกล้ x/y ที่สุด (Round to nearest, ties to even)

ต่างจาก fmod()

  • fmod: n = trunc(x/y) (ปัดทิ้งทศนิยม) → เปลี่ยนเครื่องหมายตาม x
  • remainder: n = round(x/y) (ปัดไปค่าที่ใกล้ที่สุด) → ผลลัพธ์มีค่าสัมบูรณ์ ≤ |y|/2

ตัวอย่างโค้ด

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

int main() {
    double x = 14.5, y = 4.1;
    cout << "remainder(14.5, 4.1) = " << remainder(x, y) << endl; // -1.9

    x = -34.5; y = 4.0;
    cout << "remainder(-34.5, 4.0) = " << remainder(x, y) << endl; // 1.5

    x = 65.23; y = 0;
    cout << "remainder(65.23, 0) = " << remainder(x, y) << endl; // nan

    // เปรียบเทียบกับ fmod
    cout << "fmod(14.5, 4.1) = " << fmod(14.5, 4.1) << endl; // 2.2
    cout << "remainder(14.5, 4.1) = " << remainder(14.5, 4.1) << endl; // -1.9
    return 0;
}

ผลลัพธ์

remainder(14.5, 4.1) = -1.9
remainder(-34.5, 4.0) = 1.5
remainder(65.23, 0) = nan
fmod(14.5, 4.1) = 2.2
remainder(14.5, 4.1) = -1.9

การคำนวณยืนยัน

  • 14.5 / 4.1 ≈ 3.536 → Round to nearest = 4 → 14.5 - 4×4.1 = 14.5 - 16.4 = -1.9
  • -34.5 / 4.0 = -8.625 → Round to nearest = -9 → -34.5 - (-9)×4 = -34.5 + 36 = 1.5
  • หารด้วย 0 → NaN (Domain Error)

Overloads

float remainderf(float, float);
long double remainderl(long double, long double);