I tried to incorporate the technique I had discovered for calculating the square root without utilising the sqrt function into programming.
I finally have this C++ code that runs.
#include <iostream>
using namespace std;
double SqrtNumber(double num)
{
double lower_bound=0;
double upper_bound=num;
double temp=0; /* ek edited this line */
int nCount = 50;
while(nCount != 0)
{
temp=(lower_bound+upper_bound)/2;
if(temp*temp==num)
{
return temp;
}
else if(temp*temp > num)
{
upper_bound = temp;
}
else
{
lower_bound = temp;
}
nCount--;
}
return temp;
}
int main()
{
double num;
cout<<"Enter the number\n";
cin>>num;
if(num < 0)
{
cout<<"Error: Negative number!";
return 0;
}
cout<<"Square roots are: +"<<sqrtnum(num) and <<" and -"<<sqrtnum(num);
return 0;
}
The current issue is initialising nCount in the declaratione's number of iterations ( here it is 50).
In contrast, getting the square root of 15625 requires more than 50 iterations, therefore the value of temp would be returned after 50 iterations. For instance, calculating the square root of 36 requires 22 iterations, so there is no problem.
Please offer a solution.