如何计算浮点数的 div 和 mod?
在 Perl 中,%
运算符似乎假定为整数。 例如:
sub foo {
my $n1 = shift;
my $n2 = shift;
print "perl's mod=" . $n1 % $n2, "\n";
my $res = $n1 / $n2;
my $t = int($res);
print "my div=$t", "\n";
$res = $res - $t;
$res = $res * $n2;
print "my mod=" . $res . "\n\n";
}
foo( 3044.952963, 7.1 );
foo( 3044.952963, -7.1 );
foo( -3044.952963, 7.1 );
foo( -3044.952963, -7.1 );
现在如您所见
perl's mod=6
my div=428
my mod=6.15296300000033
perl's mod=-1
my div=-428
my mod=6.15296300000033
perl's mod=1
my div=-428
my mod=-6.15296300000033
perl's mod=-6
my div=428
my mod=-6.15296300000033
,我已经提出了一个用于计算 div
和 mod
的“解决方案”。 然而,我不明白的是每个参数的符号应该对结果产生什么影响。 div
不是总是正数,即 n2
适合 n1
的次数吗? 在这种情况下,算术应该如何工作?
In Perl, the %
operator seems to assume integers. For instance:
sub foo {
my $n1 = shift;
my $n2 = shift;
print "perl's mod=" . $n1 % $n2, "\n";
my $res = $n1 / $n2;
my $t = int($res);
print "my div=$t", "\n";
$res = $res - $t;
$res = $res * $n2;
print "my mod=" . $res . "\n\n";
}
foo( 3044.952963, 7.1 );
foo( 3044.952963, -7.1 );
foo( -3044.952963, 7.1 );
foo( -3044.952963, -7.1 );
gives
perl's mod=6
my div=428
my mod=6.15296300000033
perl's mod=-1
my div=-428
my mod=6.15296300000033
perl's mod=1
my div=-428
my mod=-6.15296300000033
perl's mod=-6
my div=428
my mod=-6.15296300000033
Now as you can see, I've come up with a "solution" already for calculating div
and mod
. However, what I don't understand is what effect the sign of each argument should have on the result. Wouldn't the div
always be positive, being the number of times n2
fits into n1
? How's the arithmetic supposed to work in this situation?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
给定
a = qd + r
,在计算d
负值的余数时存在歧义。例如:
表达式
−42 ÷ −5
可以表示为:−42 = 9×(−5) + 3
或−42 = 8×(−5) + (−2)
。所以余数要么是 3,要么是 −2。
有关更多信息: Wikipedia:Remainder "余数满足的不等式"
另外,输出mod / div 中负数的情况取决于软件语言的实现。 请参阅维基百科:模运算(查看右侧的表格)
Given
a = qd + r
, there is an ambiguity when calculating the remainder for negative values ofd
.E.g.:
The expression
−42 ÷ −5
, can be expressed as either as:−42 = 9×(−5) + 3
or−42 = 8×(−5) + (−2)
.So the remainder is then either 3 or −2.
For more info: Wikipedia:Remainder "Inequality satisfied by the remainder"
Also, the output in case of negative numbers in mod / div is implementation dependent in software languages. See Wikipedia: Modulo operation (look at the table on right)
标题提出一个问题,正文提出另一个问题。 为了回答标题问题,就像在 C 中一样,% 运算符是整数模数,但有一个库例程“fmod”是浮点模数。
给出
The title asks one question, the body another. To answer the title question, just as in C, the % operator is an integer modulus, but there's a library routine "fmod" that's a floating point modulus.
gives