Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Using C++: Write a function to calculate the square root of a noar number with t

ID: 3787319 • Letter: U

Question

Using C++:


Write a function to calculate the square root of a noar number with the following interface: assert that is not egative The function should retum an approximation to using the series and xe -x/2. Then (xn xxnl/2. Keep difference between xt i is computing terms until the should stop less than 0.000 In addition, if the inpu variable x is net your function add a the via the gative, You need function call which is built-in function in to at the inning of the above function to guarantee the precondition of this function is In your main function, you need design two test cases: x-3 and x-.3 Create a screensbon demonstrate the execution of your program The specifics of the assert message shown depends on the specific implementation in the compiler, but it shall include: the

Explanation / Answer

C++ code:

#include <bits/stdc++.h>
#include <assert.h>
void print_number(int n)
{
   assert(n >= 0);
}
using namespace std;


int main()
{
   int n1 = 3;
   int n2 = -3;
   print_number(n1);
   // print_number(n2);
   double x_n = n1/2;
   // double x_n1 = 1000000;
   double x_n1 = (x_n + n1/x_n)/2;
   while(abs(x_n - x_n1) > 0.0001)
   {
       double tmp = x_n1;
       x_n1 = (x_n1 + n1/x_n1)/2;
       x_n = tmp;
   }
   cout << "Sqaure root: "<< x_n1 << endl;
   return 0;
}

Sample output:

For x = -3:

a.out: code.cpp:5: void print_number(int): Assertion `n >= 0' failed.
Aborted (core dumped)

anf for x = 3:

sqaure root : = 1.73205

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote