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

Modulus ของจำนวนจริง (float/double) ใน C

ใช้ฟังก์ชัน remainder() จาก math.h สำหรับหาเศษของการหารจำนวนจริง

สูตร

remainder(x, y) = x - rquote * y

โดย rquote = ค่า x/y ที่ปัดเป็นจำนวนเต็มใกล้เคียงที่สุด

ตัวอย่าง

#include <stdio.h>
#include <math.h>

int main() {
    double x = 14.5, y = 4.1;
    double res = remainder(x, y);
    printf("Remainder of %lf/%lf is: %lf\n", x, y, res);

    x = -34.50; y = 4.0;
    res = remainder(x, y);
    printf("Remainder of %lf/%lf is: %lf\n", x, y, res);

    x = 65.23; y = 0;
    res = remainder(x, y);
    printf("Remainder of %lf/%lf is: %lf\n", x, y, res);
    return 0;
}

ผลลัพธ์

Remainder of 14.500000/4.100000 is: -1.900000
Remainder of -34.500000/4.000000 is: 1.500000
Remainder of 65.230000/0.000000 is: -1.#IND00