我正在编写一个巴比伦算法来计算正数的平方根,并且迭代应该继续进行,直到猜测在前一个猜测的 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");
}
}
}