Using C++: Write a function to calculate the square root of a noar number with t
ID: 3787319 • Letter: U
Question
Using C++:
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
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.