|

楼主 |
发表于 2020-10-24 14:44:57
|
显示全部楼层
你再看一眼- #include <stdio.h>
- #include <string.h>
- #include <math.h>
- int main()
- {
- float x1,x2,x,y1,y2,y;
-
- float function(float x);
- float xpoint(float x1,float x2);
- float root(float x1,float x2);
- do
- {
- printf("enter the x1:\n") ;
- scanf("%f",&x1);
- printf("enter the x2:\n") ;
- scanf("%f",&x2);
- }while(function(x1) * function(x2) >= 0);
-
- do
- {
- x = xpoint(x1,x2);
- y = abs(function(x));
- x1,x2 = root(x1,x2);
- }while(y > pow(10,-6));
- printf("the root of function is %f",x);
-
- return 0;
- }
- //定义直线方程
- float function(float x)
- {
- float y;
- y = pow(x,3) - 5 * pow(x,2) + 16 * x - 80.0;
- return y;
- }
- //求两点形成的直线与x轴的交点的横坐标
- float xpoint(float x1,float x2)
- {
- float function(float x);
-
- float y1 ,y2,x,y = 0;
- y1 = function(x1);
- y2 = function(x2);
- x = ((x1 -x2)/ (y1 -y2)) * (y - y2) + x2;
- return x;
- }
- //跟新x1,x2,y1,y2
- float root(float x1,float x2)
- {
- float xpoint(float x1,float x2);
- float function(float x);
-
- float x,y,y1,y2,t;
- x = xpoint(x1,x2);
- y1 = function(x1);
- y = function(x);
- if ((y1 > 0 & y > 0) || (y1 < 0 & y < 0) )
- {
- x1 = x;
- y1 = y;
- }
- else
- {
- x2 = x;
- y2 = y;
- }
- return x1,x2;
- }
复制代码
(1) 取两个不同点x1,x2,如果f(x1)和f(x2)符号相反,则(x1,x2)区间内必有一个根。如果f(x1)与f(x2)同符号,则应改变x1,x2,直到f(x1)、f(x2)异号为止。注意x1、x2的值不应差太大,以保证(x1,x2)区间内只有一个根。
(2) 连接(x1,f(x1))和(x2,f(x2))两点,此线(即弦)交x轴于x。
(3) 若f(x)与f(x1)同符号,则根必在(x,x2)区间内,此时将x作为新的x1。如果f(x)与f(x2)同符号,则表示根在(x1,x)区间内,将x作为新的x2
(4) 重复步骤 (2) 和 (3) , 直到 |f(x)|<ε 为止, ε为一个很小的数, 例如 10-6\. 此时认为 f(x)≈0
编程思路
(1) 用函数f(x)代表x的函数:x3-5x2+16x-80.
(2) 用函数调用xpoint (x1,x2)来求(x1,f(x1))和
(x2,f(x2))的连线与x轴的交点x的坐标。
(3) 用函数调用root (x1,x2)来求(x1,x2)区间的
那个实根。显然,执行root函数过程中要用
到函数xpoint,而执行xpoint函数过程中要用
到f函数。
|
|