于是我就在课堂写作嵌套while循环来计算z的值。我需要输出z和需要得到它的时候。
下面是结果
public class TimeWhile {
public static void main(String[] args) {
int n = 100000;
int z = 1;
long startTime = System.currentTimeMillis();
int x = 0;
while (x <= n) {
int y = 0;
while (y <= n) {
z = x * y;
y++;
}
x++;
}
long endTime = System.currentTimeMillis();
long elapsed = endTime - startTime;
System.out.println("The time is " + elapsed);
System.out.println("The number is " + z);
}
}
第二while循环
public class TimeWhile {
public static void main(String[] args) {
int n = 100000;
int z = 1;
long startTime = System.currentTimeMillis();
int x = 0;
int y = 0;
while (x <= n) {
while (y <= n) {
z = x * y;
x++;
y++;
}
}
long endTime = System.currentTimeMillis();
long elapsed = endTime - startTime;
System.out.println("The time is " + elapsed);
System.out.println("The number is " + z);
}
}
为什么第二次运行得更快?输出“Z”是一样的。
我相信有很多事情是不对的代码。
首先,没有必要计算z = x * y
环路内侧,每个但最后一次迭代覆盖值。所以,你的代码实际上是一样的:
heatTheUniverseForSomeTime();
int z = n*n;
这意味着一个事实,即z
的输出是一样的,其实就是几乎一无所知的循环是如何工作的。
其次int
不够大类型持有100000*100000
的价值。这就是为什么你1410065408
,而不是更多的预期10000000000
。 long
将有助于(但要注意,你应该投至少一个参数long
右边的!)。如果你需要更大的价值,考虑BigInteger
。
第三点是,你的第一个例子可以通过使用for
循环中重新写在一个更常用,因此可以理解的形式:
for(int x = 0; x <= n; x++) {
for(int y = 0; y <= n; y++) {
z = x * y;
}
}
此代码显然需要在总运行n*n
迭代。
同时,我认为现在点#1变得更加清晰。
最后,你的第二个代码并不等同于这2个不同的方面:
y
x++;
为好,这意味着它总是认为x == y
,所以外循环的第一次迭代后从不运行为好。你第二个代码实际上是相同的
for(int x = 0, y = 0; y <= n && x <= n; x++, y++) {
z = x * y;
}
此代码显然需要只运行n
倍,而不是n*n
这是更快得多。
在第一回路y
的值总是被分配到zero
每iteration
,使得它需要更多的时间和步骤达到n
而在第二循环中,y
不重置了由此zero
它达到n更快,在更短的步骤。
LOOP1
while (x <= n) {
int y = 0;
环2
while (x <= n) {
while (y <= n) {
z = x * y;
x++;
y++;
}
第二个运行更快,因为你增加在嵌套while循环,而不是在外部时循环X。而循环运行许多比外循环多次,因为它会不断重复,直到外环的条件为假的嵌套。如果你把X的嵌套循环,就会重复多次连续,使得外环的条件为假更快。