Topic: 关于++x和x++的问题 !

  Print this page

1.关于++x和x++的问题 ! Copy to clipboard
Posted by: zxz2004
Posted on: 2006-11-20 22:50

关于++x和x++的问题始终不理解是什么意思!
public class self
{
  public static void main(String args[])
  {
    int x = 10;
     x++;
    System.out.println("x=" + x);
     ++x;
    System.out.println("x=" + x);
     x--;
     System.out.println("x=" + x);
     --x;
     System.out.println("x=" + x);
    
  }
}

结果:x=11
x=12
x=11
x=10

他们之间到底是如何自增自减的????

2.Re:关于++x和x++的问题 ! [Re: zxz2004] Copy to clipboard
Posted by: zcjl
Posted on: 2006-11-21 09:13

修改一下测试代码,再看看效果:
int x = 10;
System.out.println("x=" + x++);
System.out.println("x=" + x);
System.out.println("x=" + ++x);
System.out.println("x=" + x);
System.out.println("x=" + x--);
System.out.println("x=" + x);
System.out.println("x=" + --x);
System.out.println("x=" + x);

3.Re:关于++x和x++的问题 ! [Re: zxz2004] Copy to clipboard
Posted by: zcjl
Posted on: 2006-11-21 09:17

基本上说,++x和x++都是表达式,除了会把x + 1之外,还将返回一个数值

x++返回的是加法运算之前的x值
++x返回的是加法运算之后的x值

或者可以这样理解
x++是先返回当前x的值,再对x进行加1运算
++x是先对x进行加1运算,再返回此时x的值

4.Re:关于++x和x++的问题 ! [Re: zxz2004] Copy to clipboard
Posted by: zxz2004
Posted on: 2006-11-21 22:09

还是不懂。有QQ吗?;留一个

5.Re:关于++x和x++的问题 ! [Re: zxz2004] Copy to clipboard
Posted by: lisliefor
Posted on: 2006-11-22 15:06

。。。。。
实例:
int a = 1;
int i;
i = a++;
System.out.println(i);
i = ++a;
System.out.pringln(i);

结果分别是1和2;
zcjl 讲得非常明白了。
前者,a的自增运算会在给i赋值后;而后者自增会在i赋值之前。
i = a++; 等价与 i = a; a++;
i = ++a; 等价与 a++; i = a;

6.Re:关于++x和x++的问题 ! [Re: lisliefor] Copy to clipboard
Posted by: byzddhz
Posted on: 2006-11-22 17:16

lisliefor wrote:
实例:
int a = 1;
int i;
i = a++;
System.out.println(i);
i = ++a;
System.out.pringln(i);

结果分别是1和2;

好像结果是1和3吧。。。?
在i=a++执行完以后a就变为2了,又加一次当然是3了。

不过前面的确已经讲得很明白了。


   Powered by Jute Powerful Forum® Version Jute 1.5.6 Ent
Copyright © 2002-2021 Cjsdn Team. All Righits Reserved. 闽ICP备05005120号-1
客服电话 18559299278    客服信箱 714923@qq.com    客服QQ 714923