# include # include # include int main ( int argc, char *argv[] ) // // Purpose: // // SQUARE_ROOT2 estimates the square root of a (nonnegative) number. // // Usage: // // square_root2 s r1 // // where S is the number whose square root is desired, and R1 is an // initial guess for the root. // // If S and R1 are not given on the command line, the program will // remind the user to type them in. // { double e; double r1; double r2; double s; if ( argc < 2 ) { printf ( "Enter a number whose square root is desired: " ); scanf ( "%lf", &s ); printf ( "S = %g\n", s ); } else { s = atof ( argv[1] ); } if ( s < 0.0 ) { fprintf ( stderr, "The input number is unacceptable because it is negative.\n" ); return 1; } if ( argc < 3 ) { printf ( "Enter a guess for the square root of %g: ", s ); scanf ( "%lf", &r1 ); } else { r1 = atof ( argv[2] ); } if ( r1 == 0.0 && s != 0.0 ) { fprintf ( stderr, "A starting guess of 0 is not acceptable!\n" ); return 2; } do { r2 = s / r1; e = s - r1 * r1; printf ( " %24.16g %24.16g %g\n", r1, r2, e ); r1 = ( r1 + r2 ) / 2.0; } while ( 0.0000001 < fabs ( e ) ); return 0; }