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 doubles?
I know floating point numbers carry with them imprecision, but I’m getting the double from standard input. Maybe I should not scan it as a double straight away but as two integers instead, but where would I go from then?
The standard header
math.hdefines 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
xdivided byy. The result has the same sign as that ofx. You can user = fmod(x, y);fordoublenumbersxandy, and check ifr == 0. If you want to not test for exact divisibility but add some tolerance, then you can check ifris “close enough” to 0 ory(thanks caf).fmodf()andfmodl()are new in C99.Edit: C99 also defines a separate
remainder(double x, double y)function, that returns the remainder ofx/y. From http://docs.sun.com/source/806-3568/ncg_lib.html:…
(Either
fmod()orremainder()should work for you.)