如何使此代码不返回无限循环?

问题描述 投票:0回答:1

我想我必须使用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个回答
0
投票

boolean goAgain = false;

这永远不会设置为其他任何东西,并且循环只会在它为true时循环。>

© www.soinside.com 2019 - 2024. All rights reserved.