检查双是另一双整除用C? [英] Check if a double is evenly divisible by another double in C?
问题描述
我怎么可以检查是否双x是整除由下再双Y?用整数我只想用模,但是将与双打做正确的/最好的方法?
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?
我知道浮点数字随身携带IM precision,但我发现从标准输入的两倍。也许我不应该扫描它为双直线距离,但作为两个整数代替,但在那里我会从此走?
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?
推荐答案
标准头文件math.h
定义了以下功能:
The standard header math.h
defines the following functions:
-
双FMOD(双X,双Y);
-
浮动fmodf(浮法X,浮法Y);
-
长双fmodl(长双X,长双Y);
double fmod(double x, double y);
float fmodf(float x, float y);
long double fmodl(long double x, long double y);
这些函数返回剩余的结果X
按划分是
。其结果具有相同的符号作为 X
的。您可以使用 R = FMOD(X,Y);
为双击
数字 X
和是
,并检查是否研究== 0
。如果你想不测试的确切的可分性,但加一些宽容,那么你可以检查研究
是足够接近0或是
(感谢CAF)。
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()
和 fmodl()
在C99是新的。
的修改的:C99还定义了一个单独的余(双X,双Y)
函数,它返回 X / Y
。从<一个href=\"http://docs.sun.com/source/806-3568/ncg_lib.html\">http://docs.sun.com/source/806-3568/ncg_lib.html:
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:
的余(X,Y)
是IEEE标准754-1985指定的操作。 余(X,Y)
和 FMOD(X,Y)
之间的不同之处在于结果的符号返回通过余(X,Y)
可能无法与任何 X
或 y的符号一致
,而 FMOD(X,Y)
总是返回其符号与 X同意的结果
。这两个函数返回精确的结果,并且不会生成不精确异常。
The
remainder(x,y)
is the operation specified in IEEE Standard 754-1985. The difference betweenremainder(x,y)
andfmod(x,y)
is that the sign of the result returned byremainder(x,y)
might not agree with the sign of eitherx
ory
, whereasfmod(x,y)
always returns a result whose sign agrees withx
. Both functions return exact results and do not generate inexact exceptions.
...
在是
&NE; 0,其余的研究= X REM是
是由数学关系,无论舍入模式的定义研究= X - 纽约
,其中 N
是最近 X / Y
;每当 | N - X / Y | = 1/2
,那么 N
是偶数。因此,其余的是总是精确。如果 R = 0
,其符号应是 X
的。这个定义适用于所有的实现。
When
y
≠ 0, the remainderr = x REM y
is defined regardless of the rounding mode by the mathematical relationr = x - ny
, wheren
is the integer nearest the exact value ofx/y
; whenever| n - x/y | = 1/2
, thenn
is even. Thus, the remainder is always exact. Ifr = 0
, its sign shall be that ofx
. This definition is applicable for all implementations.
(无论是 FMOD()
或余()
应为你工作。)
(Either fmod()
or remainder()
should work for you.)
这篇关于检查双是另一双整除用C?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!