霍纳(Horner)规则是采用最少的乘法运算策略,求多项式 A(x) = a[n]x^n +
a[n-1]x^(n-1) + ... + a[1]x^1 + a[0]x^0 在x处的值。
该规则为 A(x) = (...((a[n]x + a[n-1])x + ... + a[1])x
+ a[0])。利用霍纳规则,编写C语言程序对多项式进行求值。
解:
分别用迭代和递归两种方法来实现,解题代码分别如下:
<1> 迭代:
#include
<stdio.h>
int
horner(int
*array, int
n, int x){ int result =
array[n]; while(n) { result = result * x + array[--n]; } return result;}int
main(void){ int result = 0,
i = 0, x = 0, amount = 0; do { printf("Input the amount of coefficients(include
zero.):"); scanf("%d",
&amount); }
while (amount <= 0); int a[amount]; printf("Input the
cofficients:"); for (i = 0; i <
amount; ++i) { scanf("%d", &a[i]); } printf("Input the x:"); scanf("%d",
&x); result
= horner(a, amount - 1, x); printf("The result is
:%d", result); return 0;}#include
<stdio.h>int
horner(int *array, int n, int x){ if ( !n ) { return *array; } return horner(array + 1,
n - 1, x) * x + *array;}int
main(void){ int result = 0,
i = 0, x = 0, amount = 0; do { printf("Input the amount of coefficients(include
zero.):"); scanf("%d",
&amount); }
while (amount <= 0); int a[amount]; printf("Input the
cofficients(Like:x,y,z or x y z):"); for (i = 0; i <
amount; ++i) { scanf("%d", &a[i]); } printf("Input the x:"); scanf("%d",
&x); result
= horner(a, amount - 1, x); printf("The result is
:%d", result); return 0;}
原文:http://www.cnblogs.com/xiaoniunwp/p/3594643.html