Java 增量后和增量前运算符
当我运行下面的示例时,我得到输出0,2,1Java 增量后和增量前运算符,java,scjp,ocpjp,Java,Scjp,Ocpjp,当我运行下面的示例时,我得到输出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;
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这个例子可以理解这个解决方案
public static void main(String[] args) {
int i = 0;
i = i++;
System.out.println("i is" + i);
}
/* The output is "i is 0" */
所以从这条线,
i = i++ + f1(i);
你的i仍然是1,显然函数将返回0。它再次存储在i中,因此值为1。不是将更新后的i值存储在i中,而是由赋值运算符覆盖它
i = i++ + f1(i);
i++
意味着i
现在是2
。调用f1(i)
打印2
,但返回0,因此i=2
和j=0
在这个i=1
之前,现在想象调用f1()
并替换为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+++f1(i)
语句,我们会得到如下结果
save the value of i in a temp variable, say temp1 // temp1 is 1
increment i by one (i++) // i gets the value 2
execute f1(i), save return value in, say temp2 // temp2 is 0, print 2
assign temp1 + temp2 to i // i becomes 1 again
我想主要的步骤可以总结如下。预增量意味着:向变量添加一个,并返回递增的值; 增量后-首先返回i,然后再增量它
int i, j, k;
i = 0; // 0
j = i++; // return i , then increment i
// j = 0; i = 1;
k = ++i; // first increment and return i
//k = 2; i = 2;
// now
++j == --k == --i // would be true => 1==1==1;
// but , using post increment would
// j++ == k-- == i-- // false because => 0 == 2 == 2;
// but after that statement j will be 1, k = 1, i = 1;
希望这一解释能有所帮助:
j = i++; // Here since i is post incremented, so first i being 0 is assigned to j
// and after that assignment , i is incremented by 1 so i = 1 and j = 0.
i = i++ + f1(i); // here again since i is post incremented, it means, the initial value
// of i i.e. 1 as in step shown above is used first to solve the
// expression i = i(which is 1) + f1(1)**Since i is 1**
// after this step the value of i is incremented. so i now becomes 2
// which gets displayed in your last System.out.println(i) statement.
试试这个
i = ++i + f1(i); // here i will be first inremented and then that value will be used
// to solve the expression i = i + f1(i)'
简言之,在增量后,表达式首先求解,然后值递增。但在预增量中,值首先递增,然后求解表达式
但如果你只写
i++;
++i;
那么两者的意思是一样的
在增量后运算符中,操作数的值将在使用后增加。 示例
int k =1;
int l = k++;
System.out.println("...k..."+k+"...l.."+l);
第一个k(值=1)被分配l,之后k值将增加
类似的事情发生在下面的一行
i = i++ + f1(i);
要深入了解,您需要查看及其评估顺序 这里对方程i+++f1(i)的计算进行了一些解释 在等式编译器中,获取等于1的“i”,并将其作为第一个操作数放在堆栈上,然后递增“i”,因此其值为2,并通过调用函数计算第二个操作数,该函数将为0,在执行操作时,(+)执行操作数将为1和0有关答案,请参阅常见问题部分。
int k =1;
int l = k++;
System.out.println("...k..."+k+"...l.."+l);
i = i++ + f1(i);