自由尋覓快樂別人從沒法感受

0%

C语言学习第三章T9

题目:用二分法求下面方程在(-10,10)之间的根

2x^3-4x^2+3x-6=0

主要代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
# include <stdio.h>
# include <math.h>

float fun (float ); //求方程的解的函数
float fun (float x)
{
float y;
y = 2*x*x*x-4*x*x+3*x-6;
return y;
}

int main (void)
{
float l,r,x;
do
{
printf("input x1 x2(-10~10):");
scanf("%f %f",&l,&r);
}while ( fun(l)*fun(r)>0 ); //判断输入的范围内是否有解
while ( (abs(r-l))>0.00001 ) //解的精度,可按要求调整
{
x = (l+r)/2;
if ( fun(x)>0 )
{
r = x;
}
else if ( fun(x)<0 )
{
l = x;
}
else
{
break;
}
}
printf("result:%lf\n",x);
return 0;
}

运行结果: