2013-05-19 81 views
0

我正在写一个计算正数的平方根的巴比伦算法,并且迭代应该继续下去,直到猜测在上一次猜测的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"); 
     } 
    } 
} 
+0

使用另一个'do-while'循环来代替'if-else'。另外,不要忘记继续阅读用户输入。没有火箭科学。 –

+0

此代码是否在错误小于1%之前迭代到一个?还是它也迭代错误小于1%的错误? Thakns – user2399429

+0

我的建议是**不能**使用float/double作为控件。找到一种方法来使用布尔值。答案:如果检查条件'错误'大于0.01,它会再次运行。 – ChiefTwoPencils

回答

1

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

int exit = 0; 

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

条件是'if(error <= 0.01)',而不是'if(error> 0.01)'。 – afsantos

+0

@afsantos修复它,谢谢。 – SJuan76

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 
    ); 
}