操作符系列教材 (一)- Java的算數操作符
算數操作符
基本的有:
±* / %
自增 自減
++ - -
步驟1:基本算數操作符
步驟2:練習-求和
步驟3:答案-求和
步驟4:任意運算單元的長度超過int
步驟5:任意運算單元的長度小於int
步驟6:%取模
步驟7:自增 自減
步驟8:自增 自減操作符置前以及置後的區別
步驟9:練習-自增
步驟10:答案-自增
示例 1 : 基本算數操作符
± * /
基本的加 減 乘 除
public class HelloWorld {
public static void main(String[] args) {
int i = 10;
int j = 5;
int a = i+j;
int b = i - j;
int c = i*j;
int d = i /j;
}
}
示例 4 : 任意運算單元的長度超過int
如果有任何運算單元的長度超過int,那麼運算結果就按照最長的長度計算
比如
int a = 5;
long b = 6;
a+b -> 結果類型是long
public class HelloWorld {
public static void main(String[] args) {
int a = 5;
long b = 6;
int c = (int) (a+b); //a+b的運算結果是long型,所以要進行強制轉換
long d = a+b;
}
}
示例 5 : 任意運算單元的長度小於int
如果任何運算單元的長度都不超過int,那麼運算結果就按照int來計算
byte a = 1;
byte b= 2;
a+b -> int 類型
public class HelloWorld {
public static void main(String[] args) {
byte a = 1;
byte b= 2;
byte c = (byte) (a+b); //雖然a b都是byte類型,但是運算結果是int類型,需要進行強制轉換
int d = a+b;
}
}
示例 6 : %取模
% 取餘數,又叫取模
5除以2,餘1
public class HelloWorld {
public static void main(String[] args) {
int i = 5;
int j = 2;
System.out.println(i%j); //輸出爲1
}
}
示例 7 : 自增 自減
++
在原來的基礎上增加1或者減少1
public class HelloWorld {
public static void main(String[] args) {
int i = 5;
i++;
System.out.println(i);//輸出爲6
}
}
示例 8 : 自增 自減操作符置前以及置後的區別
以++爲例
int i = 5;
i++; 先取值,再運算
++i; 先運算,再取值
public class HelloWorld {
public static void main(String[] args) {
int i = 5;
System.out.println(i++); //輸出5
System.out.println(i); //輸出6
int j = 5;
System.out.println(++j); //輸出6
System.out.println(j); //輸出6
}
}