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.)
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…