- /*
- 算数运算符:
- 1.+
- 2.-
- 3.*
- 4./
- 5.%(取模/取余)
- 6.++:自增1
- 7.--:自减1
- */
- class Demo
- {
- public static void main(String[] args)
- {
- System.out.println(5 + 3 * 2 / 3);//7
- System.out.println((5 + 3) * (6 / 2));//24
- int num1 = 20;
- int num2 = 40;
- System.out.println(num1 + num2);//60
- System.out.println((num1 + num2) * 2 + (num1 * 3));//180
- //2.关于除法
- //1).整数除法:只取商的部分,如果除不开,舍弃小数部分
- System.out.println(5 / 2);//2
- System.out.println(5 / 2.0);//2.5
- //2).除数不能为0.
- //--整数除法:编译:可以通过。运行时:出现异常。
- // System.out.println(5 / 0);//运行时异常。java.lang.ArithmeticException
- //--浮点除法:编译:通过,运行时:不会抛出异常,会打印:Infinity
- System.out.println(5 / 0.0);//Infinity
- System.out.println(5.0 / 0);//Infinity
- //3.取余:%
- System.out.println("5 % 2 = " + (5 % 2));
- System.out.println("6 % 3 = " + (6 % 3));
- // System.out.println("5 % 0 = " + (5 % 0));//运行时异常,模数不能为0
- System.out.println("5 % 0.0 = " + (5 % 0.0));//NaN:Not A Number
- //取余的结果的正负由"被模数(左操作数)"决定;
- System.out.println("-5 % -2 = " + (-5 % -2));
- System.out.println("5 % -2 = " + (5 % -2));
- System.out.println("-5 % 2 = " + (-5 % 2));
-
-
- //4.++,--运算符
- int num3 = 10;
- System.out.println("num3 = " + num3);//10
- ++num3;//将num3自增1
- System.out.println("num3 = " + num3);//11
- num3--;//将num3自减1
- System.out.println("num3 = " + num3);//10
-
- int a = 10;
- int b = 20;
- // (a + b)++;//++和--的操作数必须是一个"变量",不能是一个表达式;
- // ++5;
- //当一个表达式做多件事情时,里面 包含了++,--时,要注意前(++,--)和后(++,--)的问题
- int c = ++a;//先将a自增,然后再做其它事情:c = 11
- int d = b++;//先做其它运算,然后再自增:d = 20 b = 21
- System.out.println("c = " + c);//11
- System.out.println("d = " + d);//20
- System.out.println("a = " + a);//11
- System.out.println("b = " + b);//21
- System.out.println("程序结束!");
- }
- }
复制代码
|
|