我遇到的问题是在运行命令时理解这段代码: java 驱动程序 1000000 它的返回: 总和(1000000)= 1784293664
无论我尝试看它多久,我都无法理解代码为什么以及如何执行此操作,我只是想知道是否有人可以提供任何帮助来理解此代码对数字的实际作用?
class Sum
{
private int sum;
public int get() {
return sum;
}
public void set(int sum) {
this.sum = sum;
}
}
class Summation implements Runnable
{
private int upper;
private Sum sumValue;
public Summation(int upper, Sum sumValue) {
this.upper = upper;
this.sumValue = sumValue;
}
public void run() {
int sum = 0;
for (int i = 0; i <= upper; i++)
sum += i;
sumValue.set(sum);
}
}
public class Driver
{
public static void main(String[] args) {
if (args.length != 1) {
System.err.println("Usage Driver <integer>");
System.exit(0);
}
if (Integer.parseInt(args[0]) < 0) {
System.err.println(args[0] + " must be >= 0");
System.exit(0);
}
// Create the shared object
Sum sumObject = new Sum();
int upper = Integer.parseInt(args[0]);
Thread worker = new Thread(new Summation(upper, sumObject));
worker.start();
try {
worker.join();
} catch (InterruptedException ie) { }
System.out.println("sum(" + upper + ") = " + sumObject.get());
}
}
提前致谢
安德鲁
最佳答案
将数字 1 到 100 万相加:
(1 + 1000000) * 1000000 / 2 = 500000500000
这会导致您用来保存总和的 int
溢出。结果是:
500000500000 (mod 2^32) = 1784293664
使用long
来存储总和;它有一个 maximum value of 9223372036854775807
并且可以保存总和。
关于java - 我无法理解这个 Java 如何与我提供的参数一起工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18987789/