为什么我会从负数模运算中得到不正确的输出 [英] Why do I get an incorrect output from a modulus operation with negative number

查看:48
本文介绍了为什么我会从负数模运算中得到不正确的输出的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在Dart上尝试了以下代码:我得到28.5

  void main(){双模= -1.5%30.0;打印(模数);} 

Javascript中的相同代码返回-1.5

  let modulo = -1.5%30;console.log(modulo);  

与Dart中上面的javascript代码等效吗?

解决方案

num.remainder 说(再次强调我的意思):

此操作的结果 r 满足: this ==(this〜/other)* other + r .结果,其余的 r 与分隔符 this 的符号相同.

因此,如果您使用:

  void main(){双模=(-1.5).remainder(30.0);打印(模数);} 

您将获得 -1.5 .

请注意,两个值在数学上都是正确的;有两种不同的答案,分别对应执行整数除法时可以计算负商的两种不同方式.您可以选择将负商数舍入为零(也称为舍位)或舍入为负无穷大(底数). remainder 对应于一个截断的除法,而对应于一个底除的除法.

I tried this code on Dart: I get 28.5

void main() {
  double modulo = -1.5 % 30.0;
  print(modulo);
}

The same code in Javascript returns -1.5

let modulo =  -1.5 % 30;
console.log(modulo);

What is the equivalent of the javascript code above in Dart ?

解决方案

The documentation for num.operator % states (emphasis mine):

Returns the remainder of the Euclidean division. The Euclidean division of two integers a and b yields two integers q and r such that a == b * q + r and 0 <= r < b.abs().

...

The sign of the returned value r is always positive.

See remainder for the remainder of the truncating division.

Meanwhile, num.remainder says (again, emphasis mine):

The result r of this operation satisfies: this == (this ~/ other) * other + r. As a consequence the remainder r has the same sign as the divider this.

So if you use:

void main() {
  double modulo = (-1.5).remainder(30.0);
  print(modulo);
}

you'll get -1.5.

Note that both values are mathematically correct; there are two different answers that correspond to the two different ways that you can compute a negative quotient when performing integer division. You have a choice between rounding a negative quotient toward zero (also known as truncation) or toward negative infinity (flooring). remainder corresponds to a truncating division, and % corresponds to a flooring division.

这篇关于为什么我会从负数模运算中得到不正确的输出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆