统计信息

  • 访问数:8780
  • 博客数:142
  • 建立时间:2008-01-05
  • 更新时间:2008-05-21
我叫王超然,是一名电脑爱好者,现在在新加坡留学上高一.我立志成为一名电脑人才,愿意在这里与大家一同分享我玩转电脑的心得.O-level华文考了A-One哈哈!

P5Q19

2008-04-09 16:17:55

天气: 晴朗 心情: 高兴

/*fileName:P5Q19.java
*Name:Wang Chaoran
* Description:
19 (Approximating the square root)
Implement the sqrt method. The square root of a number, num,
can be approximated by repeatedly performing a calculation
using the following formula:
nextGuess = (lastGuess + (num / lastGuess)) / 2
When nextGuess and lastGuess are almost identical, nextGuess is the approximated square root.
The initial guess will be the starting value of lastGuess. If the difference between nextGuess
and lastGuess is less than a very small number, such as 0.0001, you can claim that nextGuess is
the approximated square root of num.
*/

public class P5Q19{
  public static void main(String[] args){
   
    double random = (int)(Math.random()*101);
    double initialGuess = (int)(Math.random()*random);
    System.out.println("The random number is: "+random+"\nThe guess for its square root is: "+initialGuess);
   
    System.out.println("The approximate of square root is: "+squareRoot(initialGuess,random));
  }
  public static double squareRoot(double lastGuess,double num){
    double nextGuess = (lastGuess + (num / lastGuess))/2;
    while ((Math.abs(nextGuess - lastGuess))>0.0001){
      lastGuess =nextGuess;
        nextGuess = (lastGuess + (num / lastGuess))/2;
    }
        return nextGuess;
  }
}
 


加入收藏 编辑 审核

TAG: computing

我来说两句

OPEN

Powered by X-Space 1.2 © 2001-2006 Comsenz Technology Ltd