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;
    }
     

         

  • 相关阅读:
    团队项目-选题报告
    第一次结对编程作业
    第一次个人编程作业
    第一次博客作业
    Java web的读取Excel简单Demo
    Java一些常见的出错异常处理
    JSTL截取字符串
    DATAX动态参数数据传递
    DataX实现oracle到oracle之间的数据传递
    DataX安装环境搭建
  • 原文地址:https://www.cnblogs.com/xiaoniunwp/p/3594643.html
Copyright © 2011-2022 走看看