Use while statement to implement Newton's method for finding the square root of a number. - CSharp Language Basics

CSharp examples for Language Basics:while

Description

Use while statement to implement Newton's method for finding the square root of a number.

Demo Code

using System;//from ww w.  j av a 2s. c o m
public class Newton {
   public static void Main( ) {
      const double epsilon   = 1.0e-9;
      double dGuess    = 11.0;

      Console.Write("Enter a positive number: ");
      double dValue = double.Parse( Console.ReadLine( ) );

      double dResult = ((dValue / dGuess) + dGuess) / 2;
      Console.WriteLine( "Guess Value  = {0}", dGuess  );
      Console.WriteLine( "Result Value = {0}", dResult );

      while( Math.Abs(dResult - dGuess) > epsilon ) {
         dGuess = dResult;
         dResult = ((dValue / dGuess) + dGuess) / 2;
         Console.WriteLine( "Guess Value  = {0}", dGuess  );
         Console.WriteLine( "Result Value = {0}", dResult );
      }
      Console.WriteLine( "\n****\nThe approx sqrt of {0} is {1}\n****", dValue, dResult );
   }
}

Result


Related Tutorials