算术运算符
Dart 支持常用的运算运算符,如下表所示:
Operator |
Meaning |
+ |
Add |
- |
Subtract |
-expr |
Unary minus, also known as negation (reverse the sign of the expression) |
* |
Multiply |
/ |
Divide |
~/ |
Divide, returning an integer result |
% |
Get the remainder of an integer division (modulo) |
示例:
assert(2 + 3 == 5);
assert(2 - 3 == -1);
assert(2 * 3 == 6);
assert(5 / 2 == 2.5); // 结果是双浮点型
assert(5 ~/ 2 == 2); // 结果是整型
assert(5 % 2 == 1); // 余数
assert('5/2 = ${5 ~/ 2} r ${5 % 2}' == '5/2 = 2 r 1');
Dart 还支持前缀和后缀,自增和自减运算符。
Operator |
Meaning |
++var |
var = var + 1 (expression value is var + 1) |
var++ |
var = var + 1 (expression value is var) |
--var |
var = var – 1 (expression value is var – 1) |
var-- |
var = var = var – 1 (expression value is var) |
示例:
var a, b;
a = 0;
b = ++a; // a自加后赋值给b。
assert(a == b); // 1 == 1
a = 0;
b = a++; // a先赋值给b后,a自加。
assert(a != b); // 1 != 0
a = 0;
b = --a; // a自减后赋值给b。
assert(a == b); // -1 == -1
a = 0;
b = a--; // a先赋值给b后,a自减。
assert(a != b); // -1 != 0