二分查找求平方根

This commit is contained in:
jinshaohui 2018-10-31 11:06:01 +08:00
parent 3b86c3dc28
commit 84602b7fd2

View File

@ -0,0 +1,53 @@
/*************************************************************************
> File Name: sqrt.c
> Author: jinshaohui
> Mail: jinshaohui789@163.com
> Time: 18-10-31
> Desc:
************************************************************************/
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
#include<assert.h>
/*求解精度设置*/
#define E 0.000001
double mybsearch(double num)
{
double start = 1.0;
double end = num;
double mid = 0.0;
while(1)
{
mid = (start + end)/2;
if(((mid*mid - num) <= E) && ((mid*mid - num) >= -E))
{
return mid;
}
if ((mid*mid - num) > E)
{
end = mid;
}
else
{
start = mid;
}
}
return 0;
}
int main()
{
double num = 0.0;
/*这里需要注意double的输入方式*/
scanf("%lf",&num);
printf("\r\n num %lf的平方根是%lf",num,mybsearch(num));
return 0;
}