go to previous page   go to home page   go to next page hear noise

Answer:

The fragment is used in front of the loop to get N, as seen below.

The improved program has the new parts shown in blue.


Potential Problem


import java.util.Scanner;
class  SquareRoot
{

  public static void main( String[] args ) 
  {
    final double smallValue = 1.0E-14 ;
    double N  ;               // the user enters a value for N
    double guess = 1.00 ;     // the same first guess works for any N

    // get the number from the user
    Scanner scan = new Scanner( System.in );
    System.out.print("Enter the number: "); 
    N = scan.nextDouble();

    while ( Math.abs( N/(guess*guess) - 1.0 ) > smallValue )
    {      
       guess =  N/(2*guess) + guess/2 ; // calculate a new guess
    }

    System.out.println("The square root of " + N + " is " + guess ) ;
  }

}

It does not hurt to initialize N in the declaration. But this might confuse a reader of the program, so it is best to not initialize N.

The program as given is largely correct, but there is a big potential problem that should be fixed.


QUESTION 19:

What would happen if the user entered a negative number?