所以我在课堂上写了一个嵌套的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”是相同的。
梦里花落0921
墨色风雨
相关分类