[英]How to find remainder of a double in C? Modulo only works for integers
This is what I've found so far online,这是我目前在网上找到的,
int main(void)
{
long a = 12345;
int b = 10;
int remain = a - (a / b) * b;
printf("%i\n", remain);
}
First I wonder how the formula works.首先我想知道这个公式是如何工作的。 Maybe i cant do math, but the priority of operations here seems a bit odd.也许我不会做数学,但这里的操作优先级似乎有点奇怪。 If i run this code the expected answer of 5 is printed.如果我运行此代码,则会打印预期答案 5。 But I dont get how (a / b) * b doesn't cancel out to 'a' leading to a - a = 0.但我不明白 (a / b) * b 如何不抵消导致 a - a = 0 的 'a'。
Now, this only works for int and long, as soon as double are involved it doesn't work anymore.现在,这只适用于 int 和 long,一旦涉及 double,它就不再起作用了。 Anyone might tell me why?谁能告诉我为什么? Is there an alternative to modulo that works for double?是否有适用于双模的替代模数?
Also I'm not sure if i understand up to what value a long can go, i found online that the upper limit was 2147483647 but when i input bigger numbers such as the one in 'a' the code runs without any issue up to a certain point...此外,我不确定我是否了解 long 可以达到什么值 go,我在网上发现上限是 2147483647,但是当我输入更大的数字(例如“a”中的数字)时,代码运行时没有任何问题,直到 a某一点...
Thanks for your help I'm new to coding and trying to learn!感谢您的帮助,我是编码和尝试学习的新手!
Given two double
finite numbers x
and y
, with y
not equal to zero, fmod(x, y)
produces the remainder of x
when divided by y
.给定两个有限double
精度数x
和y
,其中y
不等于零, fmod(x, y)
生成x
除以y
的余数。 Specifically, it returns x
− n y
, where n is chosen so that x
− n y
has the same sign as x
and is smaller in magnitude than y
.具体来说,它返回x
− n y
,其中选择n以使x
− ny y
y
具有相同的符号并且在量级上小于x
。 (So, if x
is positive, 0 ≤ fmod(x, y)
< x
, and, if x
is negative, x
< fmod(x, y)
≤ 0.) (因此,如果x
为正,则 0 ≤ fmod(x, y)
< x
,如果x
为负,则x
< fmod(x, y)
≤ 0。)
fmod
is declared in <math.h>
. fmod
在<math.h>
中声明。
A properly implemented fmod
returns an exact result;正确实施的fmod
返回准确的结果; there is no floating-point error, since the specified result is always representable.没有浮点错误,因为指定的结果总是可以表示的。
The C standard also specifies remquo
to return the remainder and some low bits (at least three) of the quotient n and remainder
with a variation on the definition of the remainder. C 标准还指定remquo
返回商n和remainder
的余数和一些低位(至少三位),但余数的定义有所不同。 It also specifies variants of these functions for float
and long double
.它还为float
和long double
指定了这些函数的变体。
Naive implementation.天真的实施。 Limited range.范围有限。 Adds additional floating point imprecisions (as it does some arithmetic)添加额外的浮点不精确度(因为它做一些算术)
double naivemod(double x)
{
return x - (long long)x;
}
int main(void)
{
printf("%.50f\n", naivemod(345345.567567756));
printf("%.50f\n", naivemod(.0));
printf("%.50f\n", naivemod(10.5));
printf("%.50f\n", naivemod(-10.0/3));
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.