java - 在循环中对奇数求和

标签 java

public static void main(String[] args) {

    int maxNum, sum, counter; // input value
    Scanner input = new Scanner(System.in); 

    System.out.print("How many odd numbers should I add up?: ");
    maxNum = input.nextInt();   

    sum = 0;

    for (counter = 1; counter < maxNum; counter++)
    {            
       sum = counter + maxNum;                        
    }

    System.out.println("\n" + "The sum of the odd numbers between 1 and " + maxNum + " is: " + sum);                 
}

根据那个特定的代码,它应该只通过奇数来解决加法问题。

现在我尝试了一个数字 5,根据我的输出:

How many odd numbers should I add up?: 5

The sum of the odd numbers between 1 and 5 is: 9

它有效。但是当我尝试另一个数字 10 时,出了点问题:

How many odd numbers should I add up?: 10

The sum of the odd numbers between 1 and 10 is: 19

我知道我的数学题,但是从 1 到 10 的奇数加起来不是 19,它加起来是 25。

代码有问题。任何人都可以找出问题所在吗?

最佳答案

   for (counter = 1; counter < maxNum; counter+=2)
   {
      sum += counter;                                 
   }

您添加了错误的号码。

关于java - 在循环中对奇数求和,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22514241/

相关文章:

java - 保存数据以在多个 Activity 中使用

java - hibernate/HSQLDB : User lacks priviledges to create constraints

java - 为什么我收到类似 : Reverting the lazy setting on the OneToOne or ManyToOne attribute? 的警告信息

java - 如何为 jsf 2.0 项目添加 nosql ( mongodb ) 支持?

java - 在 Eclipse 中启动多个进程

java - Android - 默认按钮样式

java - Android:稍后安装的主应用程序和模块

java - 使用原始类型实现通用接口(interface)

java - Spring Boot 应用程序的 loader.path 是否支持通配符模式

java - 当我在java中启动线程时,run()方法没有运行