gpt4 book ai didi

java - 如何使这段代码不返回无限循环?

转载 作者:行者123 更新时间:2023-12-02 09:05:11 26 4
gpt4 key购买 nike

我想我必须使用 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);

最佳答案

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

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

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

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

此外,根据 @Scary Wombat,boolean doagain 的值从未设置

关于java - 如何使这段代码不返回无限循环?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59870815/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com