【问题标题】:Find the sum of all odd numbers between a and b (inclusive), where both a and b are user inputs. My set_1 works but set_2 doesn't - Why?求 a 和 b(含)之间所有奇数的总和,其中 a 和 b 都是用户输入。我的 set_1 有效,但 set_2 无效 - 为什么?
【发布时间】:2020-12-27 08:35:52
【问题描述】:

注意:扫描仪在两组中都导入了

在main方法中:

代码 set_1 的开始...

    Scanner input = new Scanner(System.in); //scanner for user input
    System.out.print("Enter number, a: "); //prompt for user to enter number for variable, a
    int numA = input.nextInt(); //variable for 1st number, a
    int a = numA; //variable created to track 1st number entered - will be used to print later

    System.out.print("Enter number, b: "); //prompt for user to enter number for variable, b
    int numB = input.nextInt(); //variable for 2nd number, b


    int oddSum = 0; //variable to hold calculation of total odd sum
    //to loop between two numbers
    while (numA <= numB){
        //> 1 for odd #s to enter conditional
        if ((numA % 2) > 0){
            oddSum += numA; //variable, oddSum will store all added numbers between the 2 entered #s
        }
        numA++; //numA is counted +1
    }
    System.out.println("The sum of all odd numbers between " + a + " and " + numB + " is " + oddSum);

...代码集_1 结束 ==> 这 100% 有效

代码 set_2 的开始...

    Scanner input = new Scanner(System.in); //scanner for user input
    System.out.print("Enter number, a: "); //prompt for user to enter number for variable, a
    int numA = input.nextInt(); //variable for 1st number, a                             
    System.out.print("Enter number, b: "); //prompt for user to enter number for variable, b
    int numB = input.nextInt(); //variable for 2nd number, b


    int oddSum = 0; //variable to hold calculation of total odd sum
    int numerBetweenAandB = numA; //variable created to track 1st # entered and count up
    //to loop between two numbers
    while (numA <= numB){
        //> 1 for odd #s to enter conditional
        if ((numA % 2) > 0){
            oddSum += numberBetweenAandB; //variable, will store all added numbers between the 2 #s
        }
        numberBetweenAandB++; // counted +1
    }
    System.out.println("The sum of all odd numbers between " + numA + " and " + numB + " is " + oddSum);

...end of code set_2 ==> 这进入了一个无限循环。为什么?

我的逻辑有什么问题?据我了解 - 第一个数字存储在 numberbetweenAandB 中,并且使用 ++ 计数器上升,直到循环结束时,时间变量oddSum 已添加 a 和 b 之间的所有 #s。

感谢您为此付出的时间和精力。我还在学习。

【问题讨论】:

  • 在您的 while (numA &lt;= numB) 循环中,您不会更新 numAnumB。所以循环没有办法结束。
  • 谢谢。感谢您的澄清。我现在看到的非常明显。

标签: java if-statement conditional-statements java.util.scanner counter


【解决方案1】:

在您的代码中,您有:

while (numA <= numB){
  // a bunch of code; and none of it changes numA or numB
}

那么显然,如果这个while循环只进入一次,它将永远进入; numA 和 numB 不变,因此如果一开始为真,则永远为真。

【讨论】:

  • 谢谢。感谢您的澄清。我现在看到的非常明显。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2010-12-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-06-27
相关资源
最近更新 更多