所以我被指派编写一个程序,该程序询问一个数字 (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);
}
}
最佳答案
你需要区分
- 总结所有的
加法
一个
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;
}
关于java - 在计算 1+2+3+4...+n 时需要帮助吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60756074/