36 lines
827 B
C
36 lines
827 B
C
/*
|
||
Program: binary-search-square-root.c (Report comments/bugs to chikh@yuntech.edu.tw)
|
||
Function:
|
||
*/
|
||
|
||
#include <stdio.h>
|
||
#include <stdlib.h>
|
||
#include <math.h>
|
||
|
||
int main()
|
||
{
|
||
int i;
|
||
float x;
|
||
double a = 0, b, c;
|
||
|
||
printf("\n*** 輸入x值(x>0)計算其平方根 ***\n\n輸入x => ");
|
||
scanf("%f",&x);
|
||
b = (x < 1)? 1: x;
|
||
|
||
printf("\n二元搜尋法求解過程如下 ...\n\n迭代 區間 中間值\n"
|
||
"----+----------------------------------+----------------\n");
|
||
for (i = 0;;) {
|
||
c = (a+b)/2;
|
||
printf("#%-2d [%.10f,%.10f]\t解=%.10f\n",++i,a,b,c);
|
||
if (fabs(c*c-x) < 1e-10) break;
|
||
if (c*c < x)
|
||
a = c;
|
||
else
|
||
b = c;
|
||
}
|
||
printf("\n[二元搜尋法] sqrt(%g)=%.10f,相較於C內建函數解誤差%.1f%%\n",x,c,fabs(c-sqrt(x))/sqrt(x)*100);
|
||
|
||
system("pause");
|
||
return 0;
|
||
}
|