/ always returns a double. Use ~/ for integer division. % is the remainder.

Program

Play the program to compute integer division, remainder, and a real ratio.

arithmetic.dart
Replay: real traced execution (multi-file project)
void main() {
  var a = 7;
  var b = 2;
  var quotient = a ~/ b;
  var remainder = a % b;
  var ratio = a / b;
  print('$quotient $remainder $ratio');
}
  1. a ← 7

    1void main() {2  var a = 7;3  var b = 2;
    values this step7a
  2. b ← 2

    2var a = 7;3var b = 2;4var quotient = a ~/ b;
    values this step2b
  3. quotient ← 3

    3var b = 2;4var quotient = a ~/ b;5var remainder = a % b;
    values this step3quotient7a2b
  4. remainder ← 1

    4var quotient = a ~/ b;5var remainder = a % b;6var ratio = a / b;
    values this step1remainder7a2b
  5. ratio ← 3.5

    5var remainder = a % b;6var ratio = a / b;7print('$quotient $remainder $ratio');
    values this step3.5ratio7a2b
  6. print('$quotient $remainder $ratio');

    6  var ratio = a / b;7  print('$quotient $remainder $ratio');8}
    output3 1 3.5
    values this step3quotient1remainder3.5ratio

Follow the Math

  1. a starts at 7.
  2. b starts at 2.
  3. a ~/ b gives quotient 3.
  4. a % b gives remainder 1.
  5. a / b gives ratio 3.5, so stdout is 3 1 3.5. | expression | result | | --- | --- | | 7 ~/ 2 | 3 | | 7 % 2 | 1 | | 7 / 2 | 3.5 | | stdout | 3 1 3.5 |
~/ `~/` is truncating integer division.
% `%` returns the remainder.
/ `/` always returns a `double`, even for whole results.

Exercise: arithmetic.dart

Reproduce 3 1 3.5, then identify which operator makes each printed value.