java - 在计算 1+2+3+4...+n 时需要帮助吗?

标签 java addition calculation

所以我被指派编写一个程序,该程序询问一个数字 (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/

相关文章:

java - 在部署时连续运行类

java - 成员顺序是否会像在 C 或 C++ 中那样在 Java 中产生性能差异?

cluster-computing - 将新节点添加到 aerospike 集群

mysql - 添加 2 个文本框的值以在其中之一中显示结果

python - 查找列表中所有数字的总和 - python

java - 接口(interface)方法中的泛型被剥离

java - Jackson/Gson 的良好 REST 设计

javascript - 模 - 计算错误

python - 为什么以下代码给出不同的输出? (大数的平方根)

javascript - Vuejs/javascript 计算购物车中的商品