03. 算术运算符

Author Avatar
FengXueke 10月 18, 2022
post03

算术运算符

  1. 基本算术运算符用法
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
//: ShortCircuit.java
// Demonstrates short-circuiting behavior
// with logical operators.
package com.isflee.c03_1_3_math_ops;

import java.util.Random;

public class MathOps {


// Create a shorthand to save typing:
static void prt(String s) {
System.out.println(s);
}
// shorthand to print a string and an int:
static void pInt(String s, int i) {
prt(s + " = " + i);
}
// shorthand to print a string and a float:
static void pFlt(String s, float f) {
prt(s + " = " + f);
}
public static void main(String[] args) {
// Create a random number generator,
// seeds with current time by default:
Random rand = new Random();
int i, j, k;
// '%' limits maximum value to 99:
j = rand.nextInt() % 100;
k = rand.nextInt() % 100;
pInt("j",j); pInt("k",k);
i = j + k; pInt("j + k", i);
i = j - k; pInt("j - k", i);
i = k / j; pInt("k / j", i);
i = k * j; pInt("k * j", i);
i = k % j; pInt("k % j", i);
j %= k; pInt("j %= k", j);
// Floating-point number tests:
float u,v,w;
// applies to doubles, too
v = rand.nextFloat();
w = rand.nextFloat();
pFlt("v", v); pFlt("w", w);
u = v + w; pFlt("v + w", u);
u = v - w; pFlt("v - w", u);
u = v * w; pFlt("v * w", u);
u = v / w; pFlt("v / w", u);
// the following also works for
// char, byte, short, int, // and double:
u += v;
pFlt("u += v", u);
u -= v;
pFlt("u -= v", u);
u *= v;
pFlt("u *= v", u);
u /= v;
pFlt("u /= v", u);
}
} ///:~


  1. 自动递增和递减

++--
符号在前先加减, 符号在后后加减

  • 示例
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
//: AutoInc.java
// Demonstrates the ++ and -- operators
package com.isflee.c03_1_4_auto_inc;

public class AutoInc {

//符号在前先加减, 符号在后后加减
public static void main(String[] args) {
int i = 1;
prt("i : " + i);
prt("++i : " + ++i); // Pre-increment
prt("i++ : " + i++); // Post-increment
prt("i : " + i);
prt("--i : " + --i); // Pre-decrement
prt("i-- : " + i--); // Post-decrement
prt("i : " + i);
}
static void prt(String s) {
System.out.println(s);
}
} ///:~

1
2
3
4
5
6
7
8
输出结果
i:1
++i : 2
i++ : 2
i:3
--i : 2
i-- : 2
i:1