|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
本帖最后由 firewater 于 2015-1-19 22:53 编辑
- /*第二个代码是我自己写的,是正确的,能得到答案,第一个贴的是书上的答案,但是得不到正确答案,代码都是一样的,只是几个函数定义的位置不同,我的定义在后面,而答案的定义在前面,为什么得不到结果</span><span style="line-height: 1.5;">*/</span>
复制代码- #include <stdio.h>
- #include <math.h>
- float f(float x) /*定义f函数,以实现f(x)=x*x*x-5*x*x+16*x-80*/
- {
- float y;
- y = ((x - 5.0)*x + 16.0)*x - 80.0;
- return (y);
- }
- float xpoint(float x1, float x2) /*定义xpoint函数,求出弦与x轴的交点*/
- {
- float y;
- y = (x1*f(x2) - x2*f(x1) / (f(x2) - f(x1)));
- return (y);
- }
- float root(float x1, float x2) /*定义root函数,求近似根*/
- {
- float x, y, y1;
- y1 = f(x1);
- do
- {
- x = xpoint(x1,x2);
- y = f(x);
- if (y*y1 > 0)
- {
- y1 = y;
- x1 = x;
- }
- else
- {
- x2 = x;
- }
- } while (fabs(y) >= 0.0001);
- return (x);
- }
- void main()
- {
- float x1, x2, f1, f2, x;
- do
- {
- printf("input x1, x2:\n");
- scanf("%f%f", &x1, &x2);
- f1 = f(x1);
- f2 = f(x2);
- } while (f1 * f2 >= 0);
- x = root(x1, x2);
- printf("A root of equation is%8.4f\n", x);
- }
复制代码
以下代码是我自己写的:- #include "stdio.h"
- #include "math.h"
- int main(void)
- {
- float x1, x2, f1, f2, x;
- float f(float x); /*求函数值*/
- float xpoint(x1, x2); /*求中间变量X*/
- float root(x1, x2); /*求根*/
- do
- {
- printf("Please input two numbers :\n");
- scanf("%f%f", &x1, &x2);
- f1 = f(x1);
- f2 = f(x2);
- } while (f1*f2 >= 0);
- x = root(x1, x2);
- printf("%f", x);
- return 0;
- }
- float f(float x)
- {
- float y;
- y = x*x*x - 5.0 * x*x + 16.0 * x - 80.0;
- return (y);
- }
- float xpoint(float x1, float x2)
- {
- float y;
- y = (x1*f(x2) - x2*f(x1)) / (f(x2) - f(x1));
- return (y);
- }
- float root(float x1, float x2)
- {
- float x, y, y1;
- y1 = f(x1);
- do
- {
- x = xpoint(x1, x2);
- y = f(x);
- if (y*y1>0)
- {
- x1 = x;
- y1 = y;
- }
- else
- {
- x2 = x;
- }
- } while (fabs(y) >= 0.0001);
- return (x);
- }
复制代码
|
|