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

CSharp examples for Language Basics:do while

Description

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

Demo Code

using System;/* w  w w. j  a  v a2s.  c  o m*/
public class Newton {
   public static void Main( ) {
      const double epsilon   = 1.0e-9;
      double dGuess    = 11.0;
      double dResult   = 0.0;

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

      dResult = ((dValue / dGuess) + dGuess) / 2;

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

Result


Related Tutorials