对java代码的解释

时间:2016-02-18 01:06:51

标签: java

我知道这个问题的答案,但不理解逻辑。

我正在寻找关于最终值如何等于i=1951, j=0

的解释
int i = 60;
int j = 50;
int count = 0;
while (count < 5)
{
   i = i + i;
   i = i + 1;
   j = j - 1;
   j = j - j;
   count++;
}
System.out.println("i=" + i + ", j=" + j);

4 个答案:

答案 0 :(得分:1)

请 - 这对你自己来说很简单。付出一些努力。

count     i     j
0         121   0
1         243   0
2         487   0
3         975   0
4         1951  0

打印出逐行结果会使其足够清晰。之后,它只是加法和减法。

答案 1 :(得分:1)

您的问题有一个简单的解释:

让我们在这个循环中干运行:

count = 0 i.e. (count<5): 
i = i + i -> i = 60 + 60 = 120;
i = i + 1 -> i = 120 + 1 = 121;
j = j - 1 -> j = 50 - 1 = 49;
j = j - j -> j = 49 - 49 = 0;
count = count ++ -> count= 0 + 1 = 1;

count = 1 i.e. (count<5): 
i = i + i -> i = 121 + 121 = 242;
i = i + 1 -> i = 242 + 1 = 243;
j = j - 1 -> j = 0 - 1 = -1;
j = j - j -> j = -1 - (-1) = 0;
count = count ++ -> count= 1 + 1 = 2;

count = 2 i.e. (count<5): 
i = i + i -> i = 243 + 243 = 486;
i = i + 1 -> i = 486 + 1 = 487;
j = j - 1 -> j = 0 - 1 = -1;
j = j - j -> j = -1 - (-1) = 0;
count = count ++ -> count= 2 + 1 = 3;

count = 3 i.e. (count<5): 
i = i + i -> i = 487 + 487 = 974;
i = i + 1 -> i = 974 + 1 = 975;
j = j - 1 -> j = 0 - 1 = -1;
j = j - j -> j = -1 - (-1) = 0;
count = count ++ -> count= 3 + 1 = 4;

count = 4 i.e. (count<5): 
i = i + i -> i = 974 + 974 = 1950;
i = i + 1 -> i = 1950 + 1 = 975;
j = j - 1 -> j = 0 - 1 = -1;
j = j - j -> j = -1 - (-1) = 0;
count = count ++ -> count= 4 + 1 = 5;

循环中断现在为count = 5.

现在最终值为i = 1951,j = 0;

答案 2 :(得分:0)

您的循环体可以重写如下:

i = 2*i + 1 ;

j = 0 ;

你不必要地使循环体复杂化。

答案 3 :(得分:0)

j = 0

这是相当明显的,因为循环中的最后一个操作是j = j - j,因此无论输入如何,j之后总是为0。

i = 1951

在循环中,您执行i = i + i然后i = i + 1,因此在执行这些操作后,新i为2i + 1。你执行循环5次,所以你计算2(2(2(2(2i+1)+1)+1)+1)+1,一些简单的数学会告诉你这是1951年,如果我最初是60岁。