Given a number, n, and an approximation for its square root, a closer approximat
ID: 3779394 • Letter: G
Question
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.)
Explanation / Answer
#include<bits/stdc++.h>
using namespace std;
float squareRootOfNumber(float n)//function to find square
{
float a = n;
float y = 1;
float accuracy = 0.00001;
while(a - y > accuracy)
{
a = (a + y)/2;
y = n/a;
}
return a;
}
int main()
{
int n;
cout<<"enter number ";
cin>>n;
cout<<"Square root of "<<n<<" is "<<squareRootOfNumber(n);
}
===================================================
Output:
akshay@akshay-Inspiron-3537:~/Chegg$ g++ squareroot.cpp
akshay@akshay-Inspiron-3537:~/Chegg$ ./a.out
enter number
26
Square root of 26 is 5.09902
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.