微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

查找a和b含之间所有奇数的总和,其中a和b均为用户输入我的set_1有效,但set_2无效-为什么?

如何解决查找a和b含之间所有奇数的总和,其中a和b均为用户输入我的set_1有效,但set_2无效-为什么?

注意:两组扫描仪均已导入

在主要方法中:

代码集_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);

...代码set_1的结尾==>可以100%工作

代码集_2的开头...

    Scanner input = new Scanner(system.in); //scanner for user input
    System.out.print("Enter number,a                             
    System.out.print("Enter 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);

...代码set_2的结尾==>这会陷入无限循环。为什么?

在这里我的逻辑有什么问题?据我了解-第一个数字存储在numberbetweenAandB中,并且使用++计数器进行递增,直到循环结束为止,此时,时间变量sumSum已将a和b之间的所有#都加了。

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

解决方法

在您的代码中,您具有:

while (numA <= numB){
  // a bunch of code; and none of it changes numA or numB
}
显然,如果循环进入一次,它将永远进入。 numA和numB不会更改,因此,如果一开始是正确的,那么它将永远是真实的。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。