黑马程序员-Java算数运算符

时间:2023-02-19 13:32:54

------- android培训java培训、期待与您交流! ----------


算数运算符


黑马程序员-Java算数运算符

需要注意的:
1、取余结果的正负跟左操作的数有关,左操作数(被除数)是正,结果为正;如果左操作数 (被除数) 是负数,结果就为负。
2、对于除号“/”,它的整数除和小数除是有区别的:整数之间做除法时,只保留整数部分而舍弃小数部分;小数的话则会保留小数位

下边看例子:
class Demo 
{
	public static void main(String[] args) 
	{
		//加法
		int num1 = 2 + 3;
		int num2 = 2 + num1;
		int num3 = num1 + num2;
		System.out.println("num3="+num3);
		//+,-,*,/,跟上学的时候一样,有优先级
		System.out.println(3+3-2+9);
		System.out.println(3+9/3+9);
		System.out.println(3+3*9);
		//除法
		int a = 10;
		int b = 0;
//		System.out.println("a/b = "+a/b);//运算时异常,不能除以0
		int c = 3;
		System.out.println("a/c = "+a/c); //整数除法,结果取整
		System.out.println("a/4 = "+a/4);	//不四舍五入
		double d1 = 10;
		double d2 = 0.0;
		System.out.println("d1/d2 = " +d1/d2);//输出Infinity,无穷大
		double d3 = 4;
		System.out.println("d1/d3 = " +d1/d3);
		//取余
		int n1 = 10;
		int n2 = 5;
		int n3 = 3;
		System.out.println("n1 % n2 = "+n1 % n2);
		System.out.println("n1 % n3 = "+n1 % n3);
		int n4 = 0;
		//System.out.println("n1 % n4 = "+n1 % n4);//运行时异常不能除以0
		int n5 = -3;
		int n6 = 2;
		int n7 = -2;
		//取余结果的正负跟被除数有关,被除数是正结果为正;被除数为负结果为负。
		System.out.println("n1 % n5 = "+n1 % n5);	//1
		System.out.println("n5 % n6 = "+n5 % n6);	//-1
		System.out.println("n5 % n7 = "+n5 % n7);	//-1
		double db1 = 10;
		double db2 = 0;
		System.out.println("db1 % db2 = "+db1 % db2);	//NaN(Not a Number),不属于异常
		
		//丢失精度
		double dv1 = 64.77;
		double dv2 = 58.62;
		System.out.println("dv1 + dv2 = " + dv1 + dv2);
		//++,--
		int t1 = 10;
		t1++;
		System.out.println(t1);	//11
		++t1;
		System.out.println(t1);	//12
		int t2 = 10;
		int t3 = ++t2;
		System.out.println(t2);
		System.out.println(t3);
		int t4 = 10;
		int t5 = t4++;
		System.out.println(t4);
		System.out.println(t5);
		int t6 = 10;
		int t7 = 20;
		int t8 = t6++ + ++t7;//10 + 21 -> t8 = 31
		System.out.println(t8);
		System.out.println(t7);
		System.out.println(t6);
		int t9 = 10;
		int t10 = 20;
		System.out.println(t9--);//10
		System.out.println(t9);	//9
		//字符串连接,用+运算符
		String s1 = "a"+"b";
		System.out.println(s1);
		s1 = "a" + 10 + 20;	//左右两边有一个字符串,结果就是字符串连接
		System.out.println(s1);//a1020
		s1 = 5 + 10 + "a";
		System.out.println(s1);//15a
		s1 = 3 + "" + 2;
		System.out.println(s1);//32
		System.out.println("5 + 5=" + 5 + 5);//5 + 5 = 55
		//字符类型和整型的兼容性
		char c1 = 'a'; //ascii码 a 是97
		int t11 = c1 + 10;
		System.out.println(t11); //107
		System.out.println((char)t11);	//k 107对应ascii中的k
		System.out.println("" + c1);	//a
		System.out.println("" + c1 + 10);	//a10
		System.out.println(c1 + 10 + "");	//107
	}
}