赞
踩
//定义一个变量a
int a = 10;
//进行a++
a++;
//我们打印一下a的值
System.out.println("a的值:"+a);//11
//进行a--
a--;
System.out.println("a的值:"+a);//10
通过上方的代码可以观察到++、–操作是可以让变量的值在原有的基础上+1或-1的
int a = 10; a++;其实就等同于a=a+1;
int a = 10; a–;其实就等同于a=a-1;
//定义一个变量a int a = 10; //定义变量b,使用a++ int b = a++; //打印一下a、b的值 System.out.println("a的值:"+a);//11 System.out.println("b的值:"+b);//10 //定义一个变量a int c = 10; //定义变量d,使用c-- int d = c--; //打印一下a、b的值 System.out.println("c的值:"+c);//9 System.out.println("d的值:"+d);//10
通过以上代码运行结果发现变量b、变量d的值没有达到预想的结果,这是因为++、- - 参与运算的时候,++、- -放在变量后是先进行赋值,再进行++或- -操作的,①int a = 10; ②int b = a++; 其实这里的②可以写为两句代码,就是int b = a; a= a+1; 就是先进行赋值操作,再进行++操作
//定义一个变量a int a = 10; //定义变量b,使用++a int b = ++a; //打印一下a、b的值 System.out.println("a的值:"+a);//11 System.out.println("b的值:"+b);//11 //定义一个变量a int c = 10; //定义变量d,使用--c int d = --c; //打印一下a、b的值 System.out.println("c的值:"+c);//9 System.out.println("d的值:"+d);//9
通过以上代码可以发现++、- - 参与运算的时候放在变量前是先进行++或- - 操作,再进行赋值,①int a = 10; ②int b = ++a; 其实这里的②可以写为两句代码,就是a= a+1;int b = a; 就是先进行++,再进行赋值操作
//定义一个变量a
int a = 10;
//进行a++
a++;
//我们打印一下a的值
System.out.println("a的值:"+a);//11
//再次让a=10
a = 10;
//进行++a
++a;
//我们打印一下a的值
System.out.println("a的值:"+a);//11
1.定义变量int类型变量a = 10、b = 15、c = a++、d = ++a,计算a = ?、b = ?、c = ?、d = ?、a + --b + c++ + d = ?
//先定义a、b、c、d变量 int a = 10,b = 15,c = a++,d = ++a; /** * 分析一 * 这里做一下分析,经过赋值后的变量值 * a=10; * b=15; * (++在后)c=a=10,a=a+1=11; * (++在前)a=a+1=12,d=12 */ //定义变量接收一下最终的结果 int res = a + --b + c++ + d; /** * 分析二 * 根据运算的式子来分析,此时取分析一中的a=12,b=15,c=10,d=12 * a=12 * (--在前)b=b-1=14 * (++在后)c=c=10,然后c++,c=c+1=11 (先赋值再运算,这里参与式子的运算是c=10) * d=12 * a + --b + c++ + d = 12 + 14 + 10 + 12 = 48 */ //打印结果 System.out.println("a的值:"+a); //a的值就是分析二中所得的值 a=12 System.out.println("b的值:"+b); //b的值就是分析二中所得的值 b=14 System.out.println("c的值:"+c); //c的值就是分析二中所得的值 c=11 System.out.println("d的值:"+d); //d的值就是分析二中所得的值 d=12 System.out.println("运算的结果:"+res); // 式子的最终结果为48
类似的练习还有很多,总之遇见了n=x++;就先n=x, x=x+1,最终的n=x-1,然后再进行接下来的运算。
遇见了n=++x的就是x=x+1,n=x,最终的n=x
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。