Horner规则

霍纳(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;
}
 
<2> 递归:
#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;
}
 

     

 

转载于:https://www.cnblogs.com/xiaoniunwp/p/3594643.html

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值