public class OpCond {
public static void main(String [] args) {
int n = 10, p = 5, q = 10;
n = p = q = 5;
n += p += q;
System.out.println("A : n = " + n + " p = " + p + " q = " + q);
q = n < p ? n++ : p++;
System.out.println("B : n = " + n + " p = " + p + " q = " + q);
q = n > p ? n++ : p++;
System.out.println("C : n = " + n + " p = " + p + " q = " + q);
这是程序,当我运行它我得到q = 10(第二行),我无法弄清楚为什么 我是在纸上做的,我在第二行得到q = 5
答案 0 :(得分:1)
如果您以更全面的形式引导您的代码,也许您应该理解:
您的代码相当于:
public class OpCond {
public static void main(String [] args) {
int n = 10, p = 5, q = 10;
//n = p = q = 5;
n = 5;
p =5;
q=5;
//n += p += q;
p = p + q //so p = 10
n = n + p //so n = 15
//disp : A : n = 15 p = 10 q = 5
System.out.println("A : n = " + n + " p = " + p + " q = " + q);
//q = n < p ? n++ : p++;
if (n<p) { //false here
q = n;
n = n + 1;
}else{
q = p //q = 10
p = p + 1; // p = 11
}
//disp : B : n = 15 p = 11 q = 10
System.out.println("B : n = " + n + " p = " + p + " q = " + q);
//q = n > p ? n++ : p++;
if (n>p) { //true here
q = n; //q=15
n = n + 1; // n = 16
}else{
q = p
p = p + 1;
}
//disp : C : n = 16 p = 11 q = 15
System.out.println("C : n = " + n + " p = " + p + " q = " + q);
}
答案 1 :(得分:0)
在n += p += q;
之后,您已经明白我们为什么要打印以下内容:
A : n = 15 p = 10 q = 5
现在问题是为什么第二次印刷是:
B : n = 15 p = 11 q = 10
或具体为什么q = 10
。
答案是因为这一行:
q = n < p ? n++ : p++;
因为n> p,q被赋值为p
(三元运算符),动作p++
被称为“后增量”,这意味着它只在之后分配时发生(然后p变为11)。
答案 2 :(得分:0)
我可以从输出中看出你的意思如下
A : n = 15 p = 10 q = 5
B : n = 15 p = 11 q = 10
C : n = 16 p = 11 q = 15
q是10因为
n += p += q;
这转换为n = n + (p = p + q)
在下一行 q = n&lt; p? n ++:p ++;
转换为15 < 10 ? 15++ : 10++
(因此10将返回RHS,然后p的值将递增,因此q = 10)