首页 > 其他 > 详细

Horner规则

时间:2014-03-12 03:19:19      阅读:533      评论:0      收藏:0      [点我收藏+]

霍纳(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;
}
 

     

Horner规则,布布扣,bubuko.com

Horner规则

原文:http://www.cnblogs.com/xiaoniunwp/p/3594643.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!