Java中易出现错误的运算符
1.除:/
把握原则(小转大)
//除运算
int num1 = 12;
int num2 = 5;
int result = num1 / num2; //取整
System.out.println(result); //2
double result1 = num1 / num2; // num1 / num2为int,再赋给double
System.out.println(result1); //2.0
double result2 = num1 / num2 + 0.0; //2.0
double result3 = num1 / (num2 + 0.0); //2.4
double result4 = (double)num1 / num2; //2.4
double result5 = (double) (num1 / num2); //2.0
2.取余:%
//%:取模运算
int a = 12;
int b = 5;
System.out.println("a % b = " + a % b); //2
int a1 = -12;
int b1 = 5;
System.out.println("a1 % b1 = " + a1 % b1); //-2
int a2 = 12;
int b2 = -5;
System.out.println("a2 % b2 = " + a2 % b2); //2
int a3 = -12;
int b3 = -5;
System.out.println("a3 % b3 = " + a3 % b3); //-2
结论:结果的符号与被模数的符号相同
- 在开发中,经常使用%来判断能否被除尽的情况。
3.自增++、自减--
-
前++:先自增1,后运算。
-
后++:先运算,后自增1
//前++和后++ 、前--和后-- int x = 10; int y = ++x; System.out.println("x = " + x + ",y = " + y); //x=11,y=11 int x1 = 10; int y1 = x1++; System.out.println("x1 = " + x1 + ",y1 = " + y1); //x1=11,y1=10
-
注意:自增1不会改变变量本身的数据类型;
-
根据++的规律得出--的规律
- 前--:先自减1,后运算
- 后--:先运算,后自减1
- 单独前++,后++,结果一样
int x2 = 10;
x2++;
System.out.println(x2); //11
int x3 = 10;
++x3;
System.out.println(x3); //11