我通过运行这个简单的java程序获得了一个奇怪的输出。
输出为:0 4 2 -6
为什么x ++打印0,应该打印4。
import java.util.*;
import java.io.*;
public class Java1 {
public static void main(String[] args) throws IOException {
int x = 4;
int y = -5;
System.out.println(x++ + " " + func(x++, y) + " " + --y);
}
public static int func(int work, int y) {
int z = work + y;
work++;
y++;
System.out.print(z + " ");
return z + work + y;
}
}
答案 0 :(得分:1)
好的,这是正在进行的:首先评估x++
,返回4(稍后打印)并将x
保留为5.然后评估x++
再次,将5传递给func
。然后使用func
和5
参数评估-5
。在这里z
0
(5 + (-5) = 0
)然后打印出来(在println
方法中main
之前。func
然后返回{{ 1}}(2
)也会添加到字符串中。最后0 + 6 + (-4)
会生成--y
。现在-6
方法中的println
会打印其字符串(main
)。
答案 1 :(得分:0)
func(x++, y)
,因此0
来自System.out.print(z + " ");
中的func
。
答案 2 :(得分:0)
4 2 -6
在
之前执行System.out.print(z + " ");
因此System.out.println(x++ + " " + func(x++, y) + " " + --y);
来自0
,而不是z
。
答案 3 :(得分:0)
我在评论中提到了从0到7的点流
public static void main(String[] args) throws IOException {
int x = 4;
int y = -5;
System.out.println(x++ + " " + func(x++, y) + " " + --y);
// thus 0]4 6]2 (value returned as z) 7] localvalue of --y as -6
}
//1] x++ makes x as 5 when it is passed to func()
public static int func(int work, int y) {
int z = work + y;
//2] z = 5 + -5 = 0
work++;
//3] work which was x as 5 is now 6
y++;
//4] y will be -4 now
System.out.print(z + " ");
return z + work + y;
//5] z = 0 + 6 + -4 = 2 and is returned to func() caller
}
答案 4 :(得分:0)
import java.util.*;
import java.io.IOException;
public class Java1
{
public static void main(String args[])
{
int x = 4;
int y = -5;
System.out.println("x = "+ (x++ ) +" func = "+ (func(x++, y) ) + " y = "+ --y);
}
public static int func(int work, int y)
{
int z = work + y;// 5+-5 = 0
work++; //6
y++; //-4
System.out.print("Z = " + z + " ");//0
return z + work + y; //0 + 6+-4 = 2
}
}
输出:
Z = 0 x = 4 func = 2 y = -6
这里首先执行func(),因此变量z的值打印为0,然后x ++值打印为4.