Why I get different result with same code?

2

I wrote some dart code follow js code and there is a problem , hope someone can help me/

js code:

var max = 0x80000000;
var data = -2000;
var mod = data % max;

the mod value is -2000

Dart code :

var max = 0x80000000;
var data = -2000;
var mod = data % max;

the mod value is 2147481648

Why?

javascript
dart
asked on Stack Overflow Nov 19, 2020 by 老杂种

2 Answers

5

Because JavaScript and Dart are different languages with different operator specifications.

Dart specifies that the remainder operation result is always positive:

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:

https://www.ecma-international.org/ecma-262/11.0/index.html#sec-numeric-types-number-remainder

answered on Stack Overflow Nov 19, 2020 by Patrick
3

Dart has two "modulo" operators on integers, % (aka. modulo) and 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.

answered on Stack Overflow Nov 19, 2020 by lrn • edited Nov 20, 2020 by lrn

User contributions licensed under CC BY-SA 3.0