Check if a double is evenly divisible by another double in C?

前端 未结 7 2090
故里飘歌
故里飘歌 2020-12-10 02:41

How can I check if a double x is evenly divisible by another double y in C? With integers I would just use modulo, but what would be the correct/best way to do it with doubl

7条回答
  •  南方客
    南方客 (楼主)
    2020-12-10 03:05

    The standard header math.h defines the following functions:

    • double fmod(double x, double y);
    • float fmodf(float x, float y);
    • long double fmodl(long double x, long double y);

    These functions return the result of the remainder of x divided by y. The result has the same sign as that of x. You can use r = fmod(x, y); for double numbers x and y, and check if r == 0. If you want to not test for exact divisibility but add some tolerance, then you can check if r is "close enough" to 0 or y (thanks caf).

    fmodf() and fmodl() are new in C99.

    Edit: C99 also defines a separate remainder(double x, double y) function, that returns the remainder of x/y. From http://docs.sun.com/source/806-3568/ncg_lib.html:

    The remainder(x,y) is the operation specified in IEEE Standard 754-1985. The difference between remainder(x,y) and fmod(x,y) is that the sign of the result returned by remainder(x,y) might not agree with the sign of either x or y, whereas fmod(x,y) always returns a result whose sign agrees with x. Both functions return exact results and do not generate inexact exceptions.

    ...

    When y ≠ 0, the remainder r = x REM y is defined regardless of the rounding mode by the mathematical relation r = x - ny, where n is the integer nearest the exact value of x/y; whenever | n - x/y | = 1/2, then n is even. Thus, the remainder is always exact. If r = 0, its sign shall be that of x. This definition is applicable for all implementations.

    (Either fmod() or remainder() should work for you.)

提交回复
热议问题