#include <iostream>
#include <math.h>
using namespace std;
double func(double x){
return x * x;
}
double binary_search(double (*arr)(double), double x) {//将函数作为参数传入
double head = 0, tail = x, mid;
if(x < 1.0) tail = 1.0; // 小于1大于0的小数开根后值会变大,
#define EPSL 1e-7 //宏定义
while(tail - head > EPSL){ // 精度达到 10^(-7)
mid = (tail + head) / 2.0;
if(arr(mid) < x) head = mid;
else tail = mid;
}
#undef EPSL //结束宏定义
return mid;
}
int main(){
double n;
while(cin >> n){
cout<<"my_sqrt = "<<binary_search(func, n)<<endl;
cout<<"sqrt = "<<sqrt(n)<<endl;
}
}
对比库函数sqrt 发现结果一致