write a function to calculate Ihe square root of a float number with the followi
ID: 673500 • Letter: W
Question
write a function to calculate Ihe square root of a float number with the following interface. double square root (double x) //assert that x is not negative The function should return an approximation to square rootx using the scries approximation square root x. Let x0 = x/2 Then xn + 1=(xn + x/xn)/2 Keep computing terms until the difference between x and xn+1 is less than .0001. In addition, if the input variable x is negative, your function should stop the execution via the assert() function, which is built-in function in C++. You should add a function call to assert( ) at the beginning of the above function to guarantee the precondition of this function is correct. In your main function, you need design two test cases: x = 3 and x = -3. Create a screenshot o demonstrate the execution of your program.Explanation / Answer
float squareRoot(float n)
{
float x = n;
float y = 1;
float e = 0.000001; /* e decides the accuracy level*/
while(x - y > e)
{
x = (x + y)/2;
y = n/x;
}
return x;
}
/test case/
int main()
{
int n = 50;
printf ("Square root of %d is %f", n, squareRoot(n));
getchar();
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.