我必须创建一个代码来显示前 100000 个数字的平方,并测量程序显示每个数字所花费的时间。在我的结果中,数字有时会变为负数,然后再次变为正数。为什么是这样?我应该如何更改我的代码以使我的结果不是负面的? (前 1000 个平方数或 10000 不会发生这种情况)。
package assignment.pkg5;
import java.util.Calendar;
public class LoopsLab1000001b {
public static void main(String[] args) {
long time_start, time_finish;
time_start = time();
int count = 1;
while (count <= 100000) {
System.out.println(count * count);
count++;
}
time_finish = time();
System.out.println(time_finish - time_start + " milli seconds");
}
public static long time() {
Calendar cal = Calendar.getInstance();
return cal.getTimeInMillis();
}
}
最佳答案
整数溢出。参见 wiki ,具体来说:
In some situations, a program may make the assumption that a variable always contains a positive value. If the variable has a signed integer type, an overflow can cause its value to wrap and become negative. This overflow violates the program's assumption and may lead to unintended behavior.
关于java - 为什么我的数字在前 100000 个方格中的结果是负数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26567974/