2021-11-05 01:57

# 用二分法解方程 c语言

6-3 用二分法解方程 (20 分)

(1) x
2
−5=0

(2) x
3
−5=0

(3) sinx=0

double bisection(double (*f)(),double a,double b)

#include <stdio.h>
#include <math.h>
{
return xx-5;
}
double cubic(double x) /一个一元三次函数f/
{
return x
xx-5;
}
/

int main()
{
double x;
double a,b;
scanf("%lf%lf",&a,&b); //输入解区间左右端点的值
printf("%.3f\n",x);
x=bisection(cubic,a,b); //解一元三次方程
printf("%.3f\n",x);
x=bisection(sin,a,b); //求解方程sinx=0
printf("%.3f\n",x);
return 0;
}

1.0 4.0

2.236
1.710
3.142

4.0 6.0

-32768.000
-32768.000
-32768.000

• 写回答
• 好问题 提建议
• 追加酬金
• 关注问题
• 收藏
• 邀请回答

#### 1条回答默认 最新

已采纳
``````#include <stdio.h>
#include <math.h>
{
return x*x-5;
}
double cubic(double x) //一个一元三次函数f/
{
return x*x*x-5;
}

double bisection(double (*f)(double),double a,double b)
{
double x1 = f(a);
double x2 = f(b);
if(x1*x2>0)
return -32768;
if(fabs(x1) < 1e-3)
return a;
if(fabs(x2) < 1e-3)
return b;
double c = (a+b)/2;
double d = f(c);
while(fabs(d) > 1e-3)
{
if(d < 0)
{
if(x1<0)
a = c;
else
b = c;
}
else
{
if(x1<0)
b = c;
else
a = c;
}
c=(a+b)/2;
d = f(c);
}
return c;
}

int main()
{
double x;
double a,b;
scanf("%lf%lf",&a,&b); //输入解区间左右端点的值
printf("%.3f\n",x);
x=bisection(cubic,a,b); //解一元三次方程
printf("%.3f\n",x);
x=bisection(sin,a,b); //求解方程sinx=0
printf("%.3f",x);
return 0;
}

``````
评论
解决 1 无用
打赏 举报