Why I get different result with same code?

Viewed 71

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?

2 Answers

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.

Related