一:实验目的
- 理解秦九韶多项式求值算法的思想
- 初步熟悉用C语言编程实现该算法的过程
二:实验内容
1:秦九韶多项式求值方法
用C语言编程实现秦九韶多项式求值方法,求解 在处的值。(1):代码
```cinclude
include
int main() {
// 动态数组长度,需要输入,后续分配length个空间
int length = 0;
printf("请输入多项式系数个数:");
// #1:a0, a1, a2, ..., an
scanf_s("%d", &length);
float *array = (float *) malloc(sizeof(float) * length);
for (int i = 0; i < length; i++) {
printf("请输入第%d项系数:", i + 1);
scanf_s("%f", &array[i]);
}
// #2:x = 初值, y = an, i = n - 1
float x;
float y = array[length - 1];
printf("请输入待求式x的值:");
scanf_s("%f", &x);
// #3:y = y * x + ai
for (int i = length - 1; i > 0; i--) {
y = y * x + array[i - 1];
}
// #4:输出y
printf("最终结果为:%f", y);
free(array);
return 0;
}
### (2):运行结果
![image.png](https://cdn.nlark.com/yuque/0/2022/png/22889798/1665211461889-8daadaca-2fce-4ba8-8b5d-c0daeef3d5b4.png#clientId=u18eeef3d-32bc-4&from=paste&height=480&id=u198e58c7&originHeight=480&originWidth=960&originalType=binary&ratio=1&rotation=0&showTitle=false&size=9071&status=done&style=none&taskId=u7f695726-d737-4df2-920f-40e0340ca8c&title=&width=960)
## 2:二分法
利用二分法,求解方程。
### (1):代码
```c
#include "stdio.h"
#include "math.h"
#define f(x) (x*(x*x-1)-1)
int main() {
int i = 0;
double x, a = 1, b = 1.5, y = f(a);
if (y * f(b) >= 0) {
printf("\nThe range is error!");
return 0;
} else {
do {
x = (a + b) / 2;
printf("x%d = %6.4f\n", i + 1, x);
i++;
if (f(x) == 0) {
break;
} else if (y * f(x) < 0) {
b = x;
} else {
a = x;
}
} while (fabs(b - a) > 0.0005);
printf("\nx=%4.2f", x);
}
}
(2):运行结果
3:迭代法
(1):求方程的一个根
a:代码
#include "stdio.h"
#include "math.h"
int main() {
double x0, x1 = 1;
int i = 1;
do {
x0 = x1;
x1 = log10(x0 + 2);
printf("x%d = %6.4f\n", i, x1);
i++;
} while (fabs(x1 - x0) >= 0.0005);
printf("x = %6.4f\n", x1);
}
b:运行结果
(2):求方程在附近的根
a:代码
#include "stdio.h"
#include "math.h"
int main() {
double x0, x1 = 0.5;
int i = 1;
do {
x0 = x1;
x1 = exp(-x0);
printf("x%d = %7.5f\n", i, x1);
i++;
} while (fabs(x1 - x0) > 0.0005);
printf("x = %5.3f", x1);
}
b:运行结果
4:牛顿迭代法
(1):求方程在附近的根
a:代码
#include "stdio.h"
#include "math.h"
int main() {
double x0, x1 = 0.5;
int i = 0;
printf("x%d = %7.5f\n", i, x1);
i++;
do {
x0 = x1;
x1 = x0 - (x0 - exp(-x0)) / (1 + exp(-x0));
printf("x%d = %7.5f\n", i, x1);
i++;
} while (fabs(x1 - x0) >= 0.0005);
printf("x = %5.3f", x1);
}
b:运行结果
(2):求方程在中的根的近似值, 精度要求为
a:代码
#include "stdio.h"
#include "math.h"
int main() {
double x0, x1 = 4;
int i = 0;
printf("x%d = %5.3f\n", i, x1);
i++;
do {
x0 = x1;
x1 = x0 - ((((x0 - 2) * x0 - 4) * x0) - 7) / ((3 * x0 - 4) * x0 - 4);
printf("x%d = %5.3f\n", i, x1);
i++;
} while (fabs(x1 - x0) >= 0.01);
printf("x = %4.2f", x1);
}
b:运行结果
(3):计算的值
a:代码
#include "stdio.h"
#include "math.h"
int main() {
double x0, x1 = 11;
do {
x0 = x1;
x1 = x0 - (x0 * x0 - 115) / (2 * x0);
} while (fabs(x1 - x0) >= 0.0005);
printf("x = %5.2f", x1);
}