循环求和

鲁尼调谐器
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。

代码出了点问题。谁能找出问题所在?

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

您输入的号码有误。

本文收集自互联网,转载请注明来源。

如有侵权,请联系[email protected] 删除。

编辑于
0

我来说两句

0条评论
登录后参与评论

相关文章