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