我正在研究一种不使用sqrt函数的算法来计算平方根,并尝试将其转化为编程代码。最终,我在C++中得出了这个可行的代码。
#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;
}
现在的问题是在声明中初始化迭代次数nCount(这里为50)。例如,要找出36的平方根需要22次迭代,因此没有问题,而找到15625的平方根需要超过50次迭代,因此它将在50次迭代后返回temp的值。请提供一个解决方案。
root = pow(x,0.5);
- jrok