Post和Pre增量运算符 [英] Post and Pre increment operators
本文介绍了Post和Pre增量运算符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
当我运行以下示例时,我得到输出0,2,1
When i run the following example i get the output 0,2,1
class ZiggyTest2{
static int f1(int i) {
System.out.print(i + ",");
return 0;
}
public static void main(String[] args) {
int i = 0;
int j = 0;
j = i++; //After this statement j=0 i=1
j = j + f1(j); //After this statement j=0 i=1
i = i++ + f1(i); //i++ means i is now 2. The call f1(2) prints 2 but returns 0 so i=2 and j=0
System.out.println(i); //prints 2?
}
}
我不明白为什么输出为0, 2,1而不是0,2,2
I don't understand why the output is 0,2,1 and not 0,2,2
推荐答案
i = i++ + f1(i);
i ++
表示我
现在 2
。调用 f1(i)
打印 2
但返回0,所以 i = 2
和 j = 0
i++
means i
is now 2
. The call f1(i)
prints 2
but returns 0 so i=2
and j=0
在此 i = 1 $之前c $ c>,现在想象
f1()
调用并替换为0
before this i = 1
, now imagine f1()
called and replaced with 0
所以
i = i++ + 0;
现在它将是
i = 1 + 0 // then it will increment i to 2 and then (1 +0) would be assigned back to `i`
简单来说(来自这里 @ Piotr)
i = i ++粗略转换为
"i = i++" roughly translates to
int oldValue = i;
i = i + 1;
i = oldValue;
另一个这样的例子:
Another such Example :
- The same fundamental works here
这篇关于Post和Pre增量运算符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文