我在理解这个Java如何使用我正在提供它的参数时遇到了问题

时间:2013-09-24 17:03:48

标签: java class sum

我遇到的问题是在运行命令时理解这段代码: java Driver 1000000 它的回归: sum(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 个答案:

答案 0 :(得分:6)

总结数字1到1百万:

(1 + 1000000) * 1000000 / 2 = 500000500000

这会导致你用来保存总和的int溢出。结果是:

500000500000 (mod 2^32) = 1784293664

使用long存储总和;它有maximum value of 9223372036854775807并且可以保留总和。