【问题标题】:How can I make this code not return an infinite loop?如何使此代码不返回无限循环?
【发布时间】:2020-01-23 02:24:08
【问题描述】:

我想我必须使用 String goAgainResponse 来避免无限循环,但我不知道该代码会是什么样子。我应该通过添加 4 - 4/3 + 4/5 - 4/7 + 4/9 等来近似 pi >

      int term;
      int counter = 1;
      double piCalc=0.0;
      String goAgainResponse = null;
      boolean goAgain = false;
      Scanner kb = new Scanner(System.in);

      /* NOTE you may not declare any additional variables */

      do
      {

         System.out.println("This program will approximate Pi based on the following series:");
         System.out.println("4 - 4/3 + 4/5 - 4/7 + 4/9 - ...");

         System.out.println("Enter the term number to which you would like to approximate Pi");

         term = kb.nextInt();
         while(term <= 9)
         {
            System.out.print("Please enter a number greater than 9:");
            term = kb.nextInt();
         }

         while(term > 9)
         {
            term += 1;
            piCalc = 4/(2 * term - 1);
            System.out.print(piCalc);
         }

         System.out.print("Would you like to try again (yes/no)? ");
     }while(goAgain);

【问题讨论】:

    标签: java loops while-loop infinite-loop do-while


    【解决方案1】:
    while(term <= 9)
         {
            System.out.print("Please enter a number greater than 9:");
            term = kb.nextInt();
         }
    

    在这里,您是说 term 应该大于 9。但是您在第二个循环中的条件是 term>9 并且您在 term 中添加值,这就是为什么第二个循环是无限的

    while(term > 9)
         {
            term += 1;
            piCalc = 4/(2 * term - 1);
            System.out.print(piCalc);
         }
    

    更改第二个循环的条件将解决您的问题。或者 再次考虑term+=1

    同样根据@Scary Wombat,boolean doagain 的值永远不会设置

    【讨论】:

      【解决方案2】:

      boolean goAgain = false;

      这永远不会设置为任何其他值,并且循环仅在它为 true 时循环

      【讨论】:

        猜你喜欢
        • 2019-06-16
        • 1970-01-01
        • 2014-11-09
        • 2014-01-17
        • 2012-03-15
        • 1970-01-01
        • 2022-06-16
        • 2021-05-02
        • 2013-10-30
        相关资源
        最近更新 更多