Groovy - 算术运算符
Groovy 语言像任何语言一样支持普通的算术运算符。 以下是 Groovy 中可用的算术运算符 −
| 运算符 | 描述 | 示例 |
|---|---|---|
| + | 两个操作数相加 | 1 + 2 输出为 3 |
| − | 从第一个操作数中减去第二个操作数 | 2 − 1 输出为 1 |
| * | 两个操作数的乘法 | 2 * 2 输出为 4 |
| / | 分子除以分母 | 3 / 2 输出为 1.5 |
| % | 模运算符和整数/浮点除法后的余数 | 3 % 2 输出为 1 |
| ++ | 用于将操作数的值增加 1 的增量运算符 | int x = 5; x++; x 输出为 6 |
| -- | 用于将操作数的值减 1 的增量运算符 | int x = 5; x--; x 输出为 4 |
以下代码片段显示了如何使用各种运算符。
class Example {
static void main(String[] args) {
// Initializing 3 variables
def x = 5;
def y = 10;
def z = 8;
//Performing addition of 2 operands
println(x+y);
//Subtracts second operand from the first
println(x-y);
//Multiplication of both operands
println(x*y);
//Division of numerator by denominator
println(z/x);
//Modulus Operator and remainder of after an integer/float division
println(z%x);
//Incremental operator
println(x++);
//Decrementing operator
println(x--);
}
}
当我们运行上面的程序时,我们会得到如下结果。 从上面的算子描述可以看出,结果和预期的一样。
15 -5 50 1.6 3 5 6

