在DO-While循环停止后再做一次迭代?

时间:2013-05-19 17:58:43

标签: java

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

2 个答案:

答案 0 :(得分:1)

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

int exit = 0;

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

答案 1 :(得分: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
    );
}