因此,我被分配编写一个程序,该程序询问一个数字(n),然后进行如下加法运算:1 + 2 + 3 + 4 ... + n并输出加法运算

虽然我不断得到错误的数字,却无法弄清楚哪里出了问题?

import java.util.Scanner;

public class LukusarjanSumma {

    public static void main(String[] args) {
        Scanner reader = new Scanner(System.in);
        int addition = 0;
        System.out.println("Where to?");
        int n = Integer.valueOf(reader.nextLine());
        while (addition <= n){
            addition += addition;
            addition ++;
        } System.out.println("Total is " + addition);
    }
}

最佳答案

您需要区别对待

  • 总结所有
  • additition
  • 值递增索引的counter:1,2,3...n
    int addition = 0;
    int counter = 0;
    System.out.println("Where to?");
    int n = Integer.parseInt(reader.nextLine());
    while (counter <= n) {
        addition += counter;
        counter++;
    }
    System.out.println("Total is " + addition);
    

  • 但是更容易使用for循环,这更合乎逻辑
    int n = Integer.parseInt(reader.nextLine());
    for (int i = 0; i <= n; i++) {
        addition += i;
    }
    

    09-04 11:09