如何使用二分法实现“求一个数的平方根”?要求精确到小数点后 6 位。
//precision精确度
//a原数据
double squareRoot(double a , double precision){
double low,high,mid,tmp;
if (a>1){
low = 1;
high = a;
}else{
low = a;
high = 1;
}
while (low<=high) {
mid = (low+high)/2.000;
tmp = mid*mid;
if (tmp-a <= precision && tmp-a >= precision*-1){
return mid;
}else if (tmp>a){
high = mid;
}else{
low = mid;
}
}
return -1.000;
}
int main(int argc, const char * argv[]) {
double num = squareRoot(0.09, 0.000001);
printf("%f",num);
return 0;
}
来源:CSDN
作者:发霉的宅大人
链接:https://blog.csdn.net/Qinhaifu/article/details/104607672