Given a number n and an approximation for its square root a
Given a number, n, and an approximation for its square root, a closer approximation to the actual square root can be obtained by using this formula: new approximation=((n/ previous approximation)+ previous approximation)/2 Using the information, write a C++ program with Visual Studio 2015 that promts the user for a number and an initial guess as its square root. Using this input data, your program should be able to calculate to 0.00001. (HINT: Stop the loop when the difference between the two approximations is less than 0.00001.)
Solution
// C++ code
#include <iostream>
#include <string.h>
#include <fstream>
#include <math.h> /* asin */
#include <limits.h>
#include <cmath> // std::abs
using namespace std;
int main()
{
double n, new_approximation, previous_approximation, approximation;
cout << \"Enter n: \";
cin >> n;
cout << \"Enter approximation for its square root: \";
cin >> previous_approximation;
new_approximation=((n/ previous_approximation)+ previous_approximation)/2;
while(abs(new_approximation- previous_approximation ) > 0.00001)
{
previous_approximation = new_approximation;
new_approximation=((n/ previous_approximation)+ previous_approximation)/2;
}
cout << \"Approximated Square root: \" << new_approximation << endl;
return 0;
}
/*
output:
Enter n: 1000
Enter approximation for its square root: 29
Approximated Square root: 31.6228
*/
