The fragment is used in front of the loop to get N, as seen below.
It does not hurt, logically, to initialize N to 3.00 in the declaration. But it might confuse a reader of the program, so it is best to not initialize N.
import java.io.*;
class squareRoot
{
public static void main( String[] args ) throws IOException
{
final double smallValue = 1.0E-14 ;
double N ; // the user will supply a value for N
double guess = 1.00 ; // the same first guess will work for any N
// get the number from the user
String NChars;
BufferedReader stdin = new BufferedReader( new InputStreamReader(System.in) );
System.out.println("Enter the number:");
NChars = stdin.readLine();
N = ( Double.valueOf( NChars ) ).doubleValue();
while ( Math.abs( N/(guess*guess) - 1.0 ) > smallValue )
{
guess = N/(2*guess) + guess/2 ; // calculate a new value for the guess
}
System.out.println("The square root of " + N + " is " + guess ) ;
}
}
|
The program as given is largely correct, but there is a big potential problem that should be fixed.