为什么仅仅因为 while 循环中语句的位置发生变化,输出就会发生如此巨大的变化?
Why does the output change so drastically just because of the change in location of the statement in the while loop?
嗯,在试图理解 while 循环的全部概念时,我遇到了这个..
public static void main (String[] args) {
int x = 1;
System.out.println("Before the loop");
while(x < 4) {
x = x + 1;
System.out.println("In the loop");
System.out.println("Value of loop x is " + x);
}
System.out.println("This is after the loop");
}
这里的输出是
Before the loop
In the loop
Value of loop x is 2
In the loop
Value of loop x is 3
In the loop
Value of loop x is 4
This is after the loop
当我这样改变语句的位置时,
public static void main (String[] args) {
int x = 1;
System.out.println("Before the loop");
while(x < 4) {
System.out.println("In the loop");
System.out.println("Value of loop x is " + x);
x = x + 1;
}
System.out.println("This is after the loop");
}
输出是,
Before the loop
In the loop
Value of loop x is 1
In the loop
Value of loop x is 2
In the loop
Value of loop x is 3
This is after the loop
请向我解释为什么仅通过更改该语句的位置,输出就会发生如此巨大的变化。
如有任何帮助,我们将不胜感激...我是一个志存高远的学习者 ;)
你基本上是这样的:
x = 1
x = x + 1 // X=2
print x // X=2
--> and then to next loop
和
x = 1
print x // X=1
x = x + 1 // X=2
--> and then to next loop
所以,这真的不是很大的变化,它是值的 +1,因为你在打印之前和打印之后进行了比较
嗯,在试图理解 while 循环的全部概念时,我遇到了这个..
public static void main (String[] args) {
int x = 1;
System.out.println("Before the loop");
while(x < 4) {
x = x + 1;
System.out.println("In the loop");
System.out.println("Value of loop x is " + x);
}
System.out.println("This is after the loop");
}
这里的输出是
Before the loop
In the loop
Value of loop x is 2
In the loop
Value of loop x is 3
In the loop
Value of loop x is 4
This is after the loop
当我这样改变语句的位置时,
public static void main (String[] args) {
int x = 1;
System.out.println("Before the loop");
while(x < 4) {
System.out.println("In the loop");
System.out.println("Value of loop x is " + x);
x = x + 1;
}
System.out.println("This is after the loop");
}
输出是,
Before the loop
In the loop
Value of loop x is 1
In the loop
Value of loop x is 2
In the loop
Value of loop x is 3
This is after the loop
请向我解释为什么仅通过更改该语句的位置,输出就会发生如此巨大的变化。
如有任何帮助,我们将不胜感激...我是一个志存高远的学习者 ;)
你基本上是这样的:
x = 1
x = x + 1 // X=2
print x // X=2
--> and then to next loop
和
x = 1
print x // X=1
x = x + 1 // X=2
--> and then to next loop
所以,这真的不是很大的变化,它是值的 +1,因为你在打印之前和打印之后进行了比较