gpt4 book ai didi

java - DO-While 循环停止后再进行一次迭代吗?

转载 作者:行者123 更新时间:2023-12-01 14:33:57 24 4
gpt4 key购买 nike

我正在编写一个巴比伦算法来计算正数的平方根,并且迭代应该继续进行,直到猜测值与上一次猜测值的误差在 1% 以内。我编写的代码将迭代转到错误为 1% 之前的迭代。我怎样才能让它再进行一次迭代?为了弄清楚问题,有没有办法告诉它迭代直到误差<1%?

import java.util.Scanner;

public class sqrt {

public static void main(String[] args){
Scanner kb = new Scanner(System.in);
System.out.print("\nplease enter the desired positive number in order to find its root of two: ");

double num = kb.nextDouble();
double guess=0;
double r, g1, error;
if (num>=0){
guess = num/2;
do{
r = num/guess;
g1 = guess;
guess = (guess+r)/2;
error = (guess-g1)/guess;
if (error<0){
error = -error;
}
}

while(error>0.01);
System.out.println("The square root of the number " + num +" is equal to " +guess);

} else {
System.out.println("Sorry the number that you entered is not a positive number, and it does not have a root of two");
}
}
}

最佳答案

添加一个新计数器,该计数器仅在(以前的)退出循环条件下增加。

int exit = 0;

do {
...
if (error <= 0.01) {
exit++;
}
} while (exit < 2);

关于java - DO-While 循环停止后再进行一次迭代吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16637725/

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