0

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

2 回答 2

1

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

int exit = 0;

do {
  ...
  if (error <= 0.01) {
    exit++;
  }
} while (exit < 2);
于 2013-05-19T18:01:50.160 回答
0

如果只想在误差严格小于 1% 时返回值,则需要更改while条件。将其更改为error >= 0.01迭代,即使误差正好等于 1%,所以我们得到的最终误差小于 1%”

此外,当恰好为零时,您if (num <= 0)允许除以零。num让我们检查:

num = 0;
guess = num / 2;     // guess = 0
r = num / guess;     // r = 0 / 0

查看下面的代码应该会给您一个更清晰的想法。我已经评论过了。

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;

    // Previous code allowed a division by zero to happen.
    // You may return immediately when it's zero.
    // Besides, you ask clearly for a *positive* number.
    // You should check firstly if the input is invalid.

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

    // Since you assigned guess to zero, which is the sqrt of zero,
    // you only have to guess when it's strictly positive.

    if (num > 0) {
        guess = num/2;

        // Notice the slight change in the while condition.

        do {
            r = num/guess;
            g1 = guess;
            guess = (guess+r)/2;
            error = (guess-g1)/guess;
            if (error < 0) {
                error = -error;
            }
        } while(error >= 0.01);
    }

    // Finally, print the result.
    System.out.println(
        "The square root of the number " + num +
        " is equal to " + guess
    );
}
于 2013-05-19T18:24:46.520 回答