我是编程的新手,我无法理解这段代码

时间:2016-10-31 11:15:57

标签: java if-statement

class IfSample {
    public static void main(String args[]) {
        int x, y;
        x = 10;
        y = 20;
        if (x < y) System.out.println("x is less than y");
        x = x * 2;
        if (x == y) System.out.println("x is equal to y");
        x = x * 2;
        if (x > y) System.out.println("x is greater than y");
        if (x == y) System.out.println("x is equal to y");
    }
}

根据我的输出应该是

  

x小于y
  x等于y
  x等于y

但实际输出是

  

x小于y
  x等于y
  x大于y

请解释我怎么可能?

6 个答案:

答案 0 :(得分:4)

x = x * 2;实际上会将x * 2 的结果分配给 x

你正在申请两次。所以x依次是10,20,然后是40。

它不会以某种方式重置为10。

随着您的进步,您可能会发现等效语句x *= 2;更清晰。我做。

答案 1 :(得分:2)

我试着解释下面的代码,检查我的评论

class IfSample {
    public static void main(String args[]) {
        int x, y;//You created two variables
        x = 10;// 10 was assigned to variable x
        y = 20;// while 20 was assigned to variable y

        //you checked if x is less then y which is true cause 10 is less than 20
        if (x < y) System.out.println("x is less than y");

        x = x * 2;//You mutiplied x (which is 10) times 2 making x = 20

        //You checked if x is equal to y which is true cause x is now 20
        if (x == y) System.out.println("x is equal to y");

        x = x * 2;//You multiplied x (which is 20) by 2 given a new value of 40

        //You checked if 40 (x new value) is greater than y(value is 20) which is true
        if (x > y) System.out.println("x is greater than y");

        //This will be false cause 40 (x value) is not equal to 20 (y value) 
        if (x == y) System.out.println("x is equal to y");
    }
}

对于预期的输出,您需要这样做:

class IfSample {
    public static void main(String args[]) {
        int x, y;
        x = 10;
        y = 20;
        if (x < y) System.out.println("x is less than y");
        x = x * 2;
        if (x == y) System.out.println("x is equal to y");
        x = x * 2;
        y = y * 2;//Now y will be 40 (i.e 20 *2)
        if (x > y) System.out.println("x is greater than y");
        if (x == y) System.out.println("x is equal to y");
    }
}

答案 2 :(得分:1)

if (x > y) System.out.println("x is greater than y");

之前 对于时间,

x乘以2。

因此20 * 2 = 40 ...大于y = 20。

注意:在第一次乘法10 * 2期间,结果值20存储在变量x(内存中的位置)中。

答案 3 :(得分:0)

很简单,每次检查条件时,都要为&#39; x&#39;分配一个新值。将它乘以2。编译器逐行解释并设置最后分配的值。

答案 4 :(得分:0)

当x = 10

new.target

所以首先它打印x小于 比x = y 然后x大于y

简单地数学不是编程

答案 5 :(得分:0)

x = 10且y = 20的初始值。 执行if (x < y)后 X乘以2 i,e 10 * 2,所以现在x = 20 执行if (x == y)后 X再次乘以2 i,e 20 * 2,所以现在x = 40 所以if条件(x>y)即40> 20这是真的,因此它给出了预期的结果。