zoukankan      html  css  js  c++  java
  • 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;
    }
     

         

  • 相关阅读:
    第二阶段站立会议第三天
    第二阶段站立会议第二天
    第二阶段站立会议第一天
    测试计划
    cnblogs用户体验及建议
    第一阶段绩效评估
    第一阶段各组意见回复
    第一阶段团队评价
    站立会议第十天
    站立会议第九天
  • 原文地址:https://www.cnblogs.com/xiaoniunwp/p/3594643.html
Copyright © 2011-2022 走看看