/* Program: binary-search-solves-equation.c (Report comments/bugs to chikh@yuntech.edu.tw) Function: 利用二分搜尋法求方程式之根 */ #include #include //#define f(x) (x)*(x) #define f(x) x+sin(x)-1 //#define f(x) ((x)*exp(x))*((x)*exp(x)) double binary_search(double); int main() { float value, answer; printf("Enter the value ==> "); scanf("%f",&value); answer = binary_search(value); printf("The root = %g (Check if f(%g)=%g == %g?)\n",answer,answer,f(answer),value); return 0; } double binary_search(double y) { double a, b, mid, temp; a = 0; b = y+2; while (1) { if (a > b) break; mid = (a+b)/2.0; temp = f(mid); if (fabs(temp-y) < 1e-10) return mid; if (temp < y) a = mid; else b = mid; } return -1; }