# include # include # include using namespace std; int main ( ) // // SQROOT_CHECK estimates a square root, and checks that the number // of steps is not too large. // // We need to include because we are using the fabs() function. // // The error tolerance is too small for floating point arithmetic // when the input value is 700, for instance. // { float error, h, w, x; int step; cout << "Input the number whose square root is desired: "; cin >> x; // // Initialization. // h = x; w = x / h; error = x - h * h; step = 0; // // Loop. // while ( 0.000001 < fabs ( error ) ) { // // Increase the loop counter. // step = step + 1; if ( 100 < step ) { cerr << "\n"; cerr << "Failure!\n"; cerr << " Too many steps!\n"; cerr << " Square root estimate is " << h << "\n"; cerr << " Error is " << error << "\n"; exit ( 1 ); } h = ( h + w ) / 2.0; w = x / h; error = x - h * h; } // // We exited the loop, because our estimate beat the error estimate. // cout << "\n"; cout << "Success!\n"; cout << " Square root estimate is " << h << "\n"; cerr << " Error is " << error << "\n"; return 0; }