在招聘会中,很多面试官会要求应聘者手写代码。其中,C++手动实现sqrt()函数是一个非常常见的题目。这里,我们来为大家进行C++实现。具体的理论知识,大家可以自行搜索。
//C++重写sqrt()函数
#include <iomanip>
#include <iostream>
#include <math.h>
using namespace std;
double get_sqrt(double n)//重载库函数sqrt();
{
double small = 0;
double big = n;
while(fabs(small-big) >= 1e-6)//取浮点数相等阈值
{//利用牛顿法进行求解
small = (small+big)/2.0;
big = n/small;
}
return small;
}
int main()
{
double inp;
cin>>inp;
cout<<setiosflags(ios::fixed)<<setprecision(2);//设置输出精度
cout<<get_sqrt(inp)<<endl;
return 0;
}