【发布时间】:2014-01-18 10:12:14
【问题描述】:
我正在运行以下代码
int x=4;
int y=3;
double z=1.5;
z=++x/y*(x-- +2);
int t=(++x/y);
System.out.println(z); //7
想知道它是如何产生7的时候
- (x-- +2) =6
-
++x/y=1.6666
3=6*1.6666=10
【问题讨论】:
我正在运行以下代码
int x=4;
int y=3;
double z=1.5;
z=++x/y*(x-- +2);
int t=(++x/y);
System.out.println(z); //7
想知道它是如何产生7的时候
++x/y=1.6666
3=6*1.6666=10
【问题讨论】:
z=++x/y*(x-- +2);
被评估为:
z = ++x / y * (x-- + 2); // Substitute value of ++x, y and x--
= 5 / 3 * (5 + 2); // After this point, x will be 4. Evaluate parenthesized expr
= 5 / 3 * 7 // Now, left-to-right evaluation follows
= 1 * 7 // 5 / 3 due to integer division will give you 1, and not 1.66
和:
t = ++x / y; // x is 4 here
= 5 / 3
= 1
【讨论】:
(x-- + 2) 部分将首先被评估,但这不会对结果产生任何影响。因为++x 和x-- 的值将在评估之前被替换。
y / x++ * (x-- + 1),x-- 的值将在x++ 的值之后计算。然后(x-- + 1) 将被评估为y / x++ 之前的表达式。
代码被评估为:
z=((++x)/y)*(x-- +2);
x 和 y 都是 int 类型,所以每一步的计算结果都会转换成 int 类型。这意味着5/3=1。
最后,结果被赋值给一个双精度变量,所以7将被强制转换为7.0。
修改代码为:
z=1.0 * ((++x)/y)*(x-- +2);
你会得到一个小数的结果。
【讨论】: