游客 Signup | Login
中文 | En

1198 - C语言8.1

使用弦截法求方程f(x)=x3-5x2+16x-80=0的根。方法如下:

(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,如下图所示:

x点坐标可以用下式求出:

<img src="http://tk.hustoj.com:80/upload/pimg1235_2.gif" width="142" height="50" align="middle" alt="" />

再从x求出f(x)。

(3)<span style="font-size:7pt;">&nbsp;&nbsp;&nbsp;&nbsp; </span>若f(x)与f(x<sub>1</sub>)同符号,则根必在(x, x<sub>2</sub>)区间内,此时将x作为新的x<sub>1</sub>。如果f(x)与f(x<sub>2</sub>)同符号,则表示根在(x<sub>1</sub>,x)区间内,将x作为新的x<sub>2</sub>。

(4)<span style="font-size:7pt;">&nbsp;&nbsp;&nbsp;&nbsp; </span>重复步骤(2)和步骤(3),直到|f(x)|&lt;ε为止,ε是一个很小的数,例如10<sup>-6</sup>。此时认为f(x)≈0。

Input

两个用空格隔开的实数x1和x2,表示弦截法的区间两端。保证x1< x2,且区间内一定有解。

Output

使用弦截法计算出的方程f(x)=x3-5x2+15x-80=0的根。小数点后保留4位小数。

请注意行尾输出换行。

Examples

Input

2 6

Output

5.0000

Solution C

#include <stdio.h>
#include <math.h>
/* 定义f函数,计算题目中的函数f(x)=x3-5x2+15x-80 */
float f(float x) {
        float y;
        y = ((x - 5.0) * x + 16.0) * x - 80.0;
        return y;
}
/* 定义xpoint函数,计算弦与x轴的交点 */
float xpoint(float x1, float x2) {
        float y;
        y = (x1 * f(x2) - x2 * f(x1)) / (f(x2) - f(x1));
        return y;
}
/* 定义root函数,计算近似的根 */
float root(float x1, float x2) {
        float x, y, y1;
        y1 = f(x1);
        do {
                x = xpoint(x1, x2);
                y = f(x);
                /* 如果f(x)与f(x1)同符号 */
                if (y * y1 > 0) {
                        y1 = y;
                        x1 = x;
                } else {
                        x2 = x;
                }
        } while (fabs(y) >= 0.0001);
        return x;
}
int main() {
        float x1, x2, x;
        scanf("%f%f", &x1, &x2);
        x = root(x1, x2);
        printf("%.4f\n", x);
        return 0;
}

Solution C++

#include <stdio.h>
#include <math.h>
/* 定义f函数,计算题目中的函数f(x)=x3-5x2+15x-80 */
float f(float x) {
	float y;
	y = ((x - 5.0) * x + 16.0) * x - 80.0;
	return y;
}
/* 定义xpoint函数,计算弦与x轴的交点 */
float xpoint(float x1, float x2) {
	float y;
	y = (x1 * f(x2) - x2 * f(x1)) / (f(x2) - f(x1));
	return y;
}
/* 定义root函数,计算近似的根 */
float root(float x1, float x2) {
	float x, y, y1;
	y1 = f(x1);
	do {
		x = xpoint(x1, x2);
		y = f(x);
		/* 如果f(x)与f(x1)同符号 */
		if (y * y1 > 0) {
			y1 = y;
			x1 = x;
		} else {
			x2 = x;
		}
	} while (fabs(y) >= 0.0001);
	return x;
}
int main() {
	float x1, x2, x;
	scanf("%f%f", &x1, &x2);
	x = root(x1, x2);
	printf("%.4f\n", x);
	return 0;
}

Time Limit 1 second
Memory Limit 32 MB
Discuss Stats
上一题 下一题