Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Lập Trình C

Phép modulus của hai số float/double trong C

Ở đây ta sẽ xem cách lấy modulus (phần dư) của hai số thực float hoặc double trong C. Dùng hàm remainder() trong C. Hàm này tính phần dư dấu ch động của tử/mẫu.

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

Trong đó rquote là giá trị x/y làm tròn đến số nguyên gần nhất. Hàm nhận 2 đối số kiểu double, float, long double, trả về phần dư cùng kiểu. Tham số đầu là tử, tham số hai là mẫu.

Ví dụ

#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;
}

Kết quả

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