我叫王超然,是一名电脑爱好者,现在在新加坡留学上高一.我立志成为一名电脑人才,愿意在这里与大家一同分享我玩转电脑的心得.O-level华文考了A-One哈哈!
天气: 晴朗
心情: 高兴
/*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;
}
}
导入论坛查看(43)回复(0)引用(0)好评(0) 差评(0)
加入收藏
编辑
审核
TAG:
computing