Data_Structure/作業/老師解答/unit1/binary-search-solves-equation.c

47 lines
790 B
C
Raw Permalink Normal View History

2025-01-20 21:25:33 +08:00
/*
Program: binary-search-solves-equation.c (Report comments/bugs to chikh@yuntech.edu.tw)
Function: <EFBFBD>Q<EFBFBD>ΤG<EFBFBD><EFBFBD><EFBFBD>j<EFBFBD>M<EFBFBD>k<EFBFBD>D<EFBFBD><EFBFBD><EFBFBD>{<EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>
*/
#include <stdio.h>
#include <math.h>
//#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;
}