/* CS 1711B Class; 1998/10/2 To find the square root of a positive number A by iteration of x_n = x_(n-1)/2 + A/(2*x_(n-1). file: iter-rt.cpp */ #include #include #include main() { double A, xzero, // initial estimate tolerance, xnow, xprev; // intermediate values int max_iter, // maximum and counts of iterations iter; cout << endl << endl; cout << "Approximates the square root of A from xzero within tolerance\n"; cout << "using at most max iterations\n\n"; cout << "Input A, xzero, tolerance, max iterations>" << endl; cin >> A>> xzero>> tolerance>> max_iter; // bad input trap while ( (A < 0.0) || (xzero < 0.0) || (tolerance < 0.0) || (max_iter < 0)) { cout << "All values must be positive, try again!\n"; cout << "Input A, xzero, tolerance, max iters>" << endl; cin >> A>> xzero>> tolerance>> max_iter; } iter = 0; xprev = xzero; xnow = xzero; while ( (fabs(A - xnow*xnow) >= tolerance) && (iter < max_iter)) { iter++; xnow = xprev/2.0 + A/(2.0*xprev); xprev = xnow; } if ( iter >= max_iter ) cout << "\nFailure: too many iterations used, but ..." << endl; cout << "\nThe calculated approximation after " << iter << " iterations " <