using System; namespace PS3_Q1 { // // Problem Set 3, Question 1 // Written by Paul Hudak // October 4, 2006 // class Class1 { // // Program Design Exercise 17 in Chapter 4. // Computer the square root of a number typed by the user, // using a method due to the ancient Babylonians. // [STAThread] static void Main(string[] args) { // get non-negative number from user double x = GetNumber(); // initialize variables int count; // keeps track of number of loops double est = 1; // first estimate double old = 0; // old estimate // perform the Babylonians' algorithm for( count = 0; Math.Abs(old-est) > 1.0e-6; count = count+1 ) { old = est; est = (x/est + est)/2; } // display result Console.WriteLine("\nThe square root of {0} is {1},\n" + "which took {2} iterations to compute.\n", x, est, count); } public static double GetNumber() { // get a non-negative number from the user Console.Write("Please type a non-negative number: "); double x = double.Parse(Console.ReadLine()); // if x<0, ignore it and ask for a new number while (x<0) { Console.Write("Negative numbers are not allowed.\n" + "Please try again: "); x = double.Parse(Console.ReadLine()); } return x; } } }