-3

我正在计算两个界限之间的总和(使用增量),但我没有得到适当的输出:

示例 1:

First: 3
Last: 5
Sum is: 12

示例 2:

First: 2
Last: 8
Sum is: 35

这是我正在使用的代码:

public static void main(String[] args) {
    // TODO code application logic here
    Scanner reader = new Scanner(System.in);
    System.out.print("First: ");
    int x = Integer.parseInt(reader.nextLine());
    System.out.print("Second: ");
    int y = Integer.parseInt(reader.nextLine());
    int i = x;
    int result = 0;

    while (i < y){
        result += i + 1;
        i++;

        System.out.println("Sum is " + result);

错误的输出:

First: 3
Second: 5
Sum is: 9
4

1 回答 1

1

您实际上跳过了添加3

result += i + 1;
i++;

在您的 3, 5 示例中i以 开头3,并且由于您的第一次迭代添加i+1到您的result,您正在添加4

在您的最后一次迭代中,i将是 4,并且您将添加4+1result,这就是您的实际结果3小于预期结果的原因。

如果我是你,我会像这样构建你的结果

for(int i = x; i<= y; i++)
{
    result += i;
}

*由于您的while循环在每次迭代后打印增量总和,您应该已经看到了这种行为。

于 2013-11-13T18:37:57.490 回答