#include<math.h>
typedef double(*fun)(double xx)//函数指针
#define e 0.000001 //误差
void eff(double a,double b,fun hs)//二分法
{int i=0
while(fabs(hs(a)-hs(b))>e&&fabs(a-b)>e){i++
if(hs(a)*hs((b+a)/2)>0){
a=(a+b)/2
printf("迭代第%d次:\t%f\n",i,a)
}
else {
b=(a+b)/2
printf("迭代第%d次:\t%f\n",i,b)
}
}
}
double hs1(double xx)//函数f(x)=x^3+x^2-3x-3
{return xx*xx*xx+xx*xx-3*xx-3}
double hs2(double xx)//函数f(x)=lnx+x
{return log(xx)+xx}
void main()
{
printf("用二分法求方程x^3+x^2-3x-3=0在1.5附近的根\n")
eff(1.0,2.0,hs1)
printf("用二分法求方程lnx+x在0.5附近的根\n")
eff(0.0,1.0,hs2)
}
#include <stdio.h>
#include <math.h>
double fun_math(double)
int main(void)
{
/* 根据函数可知Y是关于x的一个递增函数 */
/* 先判断输入Y时,X在(0,1)时是否有解 */
double Y
double X=0 ,big_x=1.0,small_x=0,tmp_X=1
unsigned int tmp=0
printf("Please enter Y:")
scanf("%lf",&Y)
if(fun_math(1) >= Y &&fun_math(0) <= Y)
{
while(tmp_X != X)
{
X =(big_x + small_x)/2
if(fun_math(X)==Y) break
if(fun_math(X)>Y) big_x = X
else small_x = X
tmp_X = X
X =(big_x + small_x)/2
}
printf("X = %.6lf",X)
}
else printf("while Y=%lf, X(0,1) on results\n",Y)
return 0
}