我正在写一个计算正数的平方根的巴比伦算法,并且迭代应该继续下去,直到猜测在上一次猜测的1%以内。 我写的代码在错误为1%之前获得迭代。我怎样才能让它做更多的迭代? 直接得到问题,有没有办法告诉它迭代直到错误是< 1%?DO-While循环停止后再做一次迭代?
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");
}
}
}
使用另一个'do-while'循环来代替'if-else'。另外,不要忘记继续阅读用户输入。没有火箭科学。 –
此代码是否在错误小于1%之前迭代到一个?还是它也迭代错误小于1%的错误? Thakns – user2399429
我的建议是**不能**使用float/double作为控件。找到一种方法来使用布尔值。答案:如果检查条件'错误'大于0.01,它会再次运行。 – ChiefTwoPencils