[英]Why I get different result with same code?
I wrote some dart code follow js code and there is a problem , hope someone can help me/我按照js代码写了一些dart代码,有问题,希望有人能帮助我/
js code: js代码:
var max = 0x80000000;
var data = -2000;
var mod = data % max;
the mod value is -2000 mod 值为 -2000
Dart code :飞镖代码:
var max = 0x80000000;
var data = -2000;
var mod = data % max;
the mod value is 2147481648 mod 值为 2147481648
Why?为什么?
Because JavaScript and Dart are different languages with different operator specifications.因为 JavaScript 和 Dart 是不同的语言,具有不同的运算符规范。
Dart specifies that the remainder operation result is always positive: Dart 指定余数运算结果始终为正:
https://api.dart.dev/stable/2.10.4/dart-core/num/operator_modulo.html https://api.dart.dev/stable/2.10.4/dart-core/num/operator_modulo.html
In JavaScript the remainder can be negative, the sign of the result equals the sign of the dividend:在 JavaScript 中,余数可以是负数,结果的符号等于被除数的符号:
https://www.ecma-international.org/ecma-262/11.0/index.html#sec-numeric-types-number-remainder https://www.ecma-international.org/ecma-262/11.0/index.html#sec-numeric-types-number-remainder
Dart has two "modulo" operators on integers, %
(aka. modulo) and remainder
. Dart 在整数上有两个“模”运算符, %
(又名模)和remainder
。
They differ for negative operands in whether the result takes the sign of the dividend or the divisor.对于负操作数,它们的不同在于结果是被除数还是除数的符号。 For positive operands the two agree.对于正操作数,两者一致。
Compare:相比:
void main() {
for (var a in [5, -5]) {
for (var b in [3, -3]) {
print("$a ~/ $b = ${a ~/ b}");
print("$a % $b = ${a % b}");
print("$a.remainder($b) = ${a.remainder(b)}");
print("$a = $b * ($a ~/ $b) + $a.remainder($b) = ${b * (a ~/ b) + a.remainder(b)}");
}
}
}
This code shows all the combinations and that a == (a ~/ b) * b + a.remainder(b)
in general.此代码显示了所有组合,并且a == (a ~/ b) * b + a.remainder(b)
一般。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.