6-2 多项式求值:循环、递归两种实现方式

54 阅读1分钟

题目:

本题要求实现一个函数,计算阶数为n,系数为a[0] ... a[n]的多项式f(x)=∑i=0n​(a[i]×xi) 在x点的值。

函数接口定义: double f( int n, double a[], double x );

其中n是多项式的阶数,a[]中存储系数,x是给定点。函数须返回多项式f(x)的值。

pintia.cn/problem-set…

解答:

一:循环

网上很多答案了,没什么好说的,注意tmp的值不要搞错即可

double f( int n, double a[], double x )
{
    // sum: 存储最终结果;初始化为 a[0] 是为了简化计算
    // tmp: 存储 x^i
    double sum = a[0], tmp = 1;
    
    int i;
    // sum 初始化为 a[0],所以从 a[1] * (x^1) 开始计算,i 从 1 开始循环          
    for (i = 1; i <= n; i++)
    {
        // 每次 i 加一,tmp就乘以 x,确保 x^i 和 a[i] 的 i 相等
        tmp *= x;
        
        sum += a[i] * tmp;
    }
 
    return sum;
}

二:递归

思路:f(0) = a[0]; f(n) = f(n - 1) + a[n] * x^n

// 因为是递归所以用不了tmp,需要直接使用幂函数
#include <math.h>
 
double f( int n, double a[], double x )
{
    if (n == 0)
        return a[0];
    
    return f(n - 1, a, x) + a[n] * pow(x, n);
}