我做错了什么?我真的不确定要尝试什么,或者我的错误在哪里。谢谢你的帮助。它应该计算两个数字之间的整数之和,例如在3到6之间将是3 + 4 + 5 + 6

import java.util.Scanner;
public class TheSumBetweenTwoNumbers {
    public static void main(String[] args) {
        Scanner reader = new Scanner(System.in);

        System.out.println("First:");
        int n = Integer.parseInt(reader.nextLine());

        System.out.println("Second:");
        int max = Integer.parseInt(reader.nextLine());

        int sum = 0;
        int i = 0;
        int difference  = max - n;

        while (i < difference) {
            sum = n + (n + 1);
            n++;
            i++;

        }

        System.out.println("Sum is " + sum);
    }
}

最佳答案

为什么所有这些都只需要这样的一段代码:

public static void main(String args[]) {
    int min = 3, max = 6, sum = 0;
    for (int i = min; i <= max; i++) {
        sum += i;
    }
    System.out.println(sum);
}


使用while循环应该是:

...
int i = min;
while (i <= max) {
    sum += i;
    i++;
}
...

关于java - 计算两个整数之间的和(java),我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/43596874/

10-11 20:26
查看更多