Basics
Arithmetic
~/, %, /
/ 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');
}
a ← 7
1void main() {2 var a = 7;3 var b = 2;values this step7ab ← 2
2var a = 7;3var b = 2;4var quotient = a ~/ b;values this step2bquotient ← 3
3var b = 2;4var quotient = a ~/ b;5var remainder = a % b;values this step3quotient7a2bremainder ← 1
4var quotient = a ~/ b;5var remainder = a % b;6var ratio = a / b;values this step1remainder7a2bratio ← 3.5
5var remainder = a % b;6var ratio = a / b;7print('$quotient $remainder $ratio');values this step3.5ratio7a2bprint('$quotient $remainder $ratio');
6 var ratio = a / b;7 print('$quotient $remainder $ratio');8}output3 1 3.5values this step3quotient1remainder3.5ratio
Follow the Math
astarts at7.bstarts at2.a ~/ bgives quotient3.a % bgives remainder1.a / bgives ratio3.5, so stdout is3 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.