Data_Structure/作業/老師解答/unit1/binary-search-square-root.c
2025-01-20 21:25:33 +08:00

36 lines
827 B
C
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

/*
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;
}