Java 中的 %= 运算符
    
    
            Mohammad Irfan
    2023年10月12日
    
    Java
    Java Operator
    
 
本教程介绍了 %= 运算符的含义以及如何在 Java 中使用它。
%= 运算符是一个组合运算符,由 %(取模)和 =(赋值)运算符组成。这首先计算模,然后将结果分配给左操作数。
此运算符也称为速记运算符,用于使代码更简洁。在本文中,我们将通过示例学习如何使用此运算符。
那么,让我们开始吧。
Java 中的模运算符
在此示例中,我们使用模运算符来获取值的余数,然后将其赋值以使用赋值运算符。
public class SimpleTesting {
  public static void main(String[] args) {
    int val = 125;
    int result = val % 10;
    System.out.println("Remainder of " + val + "%10 = " + result);
  }
}
输出:
Remainder of 125%10 = 5
Java 中的速记模运算符
现在,让我们使用速记运算符来获取余数。代码简洁并产生与上述代码相同的结果。
public class SimpleTesting {
  public static void main(String[] args) {
    int val = 125;
    int temp = val;
    val %= 10; // compound operator
    System.out.println("Remainder of " + temp + "%10 = " + val);
  }
}
输出:
Remainder of 125%10 = 5
Java 中的速记运算符
Java 支持+=、-=、*=等其他几种复合赋值运算符,在本例中,我们使用了其他的速记运算符,以便你更好地理解这些运算符的使用。
请参阅下面的示例。
public class SimpleTesting {
  public static void main(String[] args) {
    int val = 125;
    System.out.println("val = " + val);
    val += 10; // addition
    System.out.println("val = " + val);
    val -= 10; // subtraction
    System.out.println("val = " + val);
    val *= 10; // multiplication
    System.out.println("val = " + val);
    val /= 10; // division
    System.out.println("val = " + val);
    val %= 10; // compound operator
    System.out.println("val = " + val);
  }
}
输出:
val = 125
val = 135
val = 125
val = 1250
val = 125
val = 5
        Enjoying our tutorials? Subscribe to DelftStack on YouTube to support us in creating more high-quality video guides. Subscribe