如何修复我的e ^ x近似C程序?

bel*_*_st 3 c math function output

我编写了一个C程序,它应该计算并打印所有n值的e ^ x近似值.我正在使用这个等式来实现我的程序.

f(x,n)= e ^ x = i = 0到n = x ^ i/x之和!= x ^ 0/0!+ x ^ 1/1!+ x ^ 2/2!+ .... + x ^ n/n!

这是我的代码:

#include <stdio.h>
#include <math.h>
#include <stdlib.h>

double factorial(int n){
        double fac =1;
        int i;
        for(i =1; i <= n; i++){ 
                fac *=n;
        }
        return fac;
}
double exponent(double x, int n){
        double sum, i;
        for(i = 0; i <=n; i++){
                sum +=  (pow(x, i)/ factorial(i));
        } 
        return sum;
}

int main(int argc, char *argv[]){
        int n = atoi(argv[1]);
        double x = atof(argv[2]);
        printf("\ti\tApproximantion\n");
        printf("-------------------------------------\n");
        int i;
        for(i =0; i <=n; i++){
               printf("\t%d\t%f\n", i, exponent(x,i));
        }
        printf("Exact Value =\t%12f\n", exp(x));
        return 0;
}//main
Run Code Online (Sandbox Code Playgroud)

我使用迭代而不是递归.我目前使用的输出./aprroximation 10 2.2是:

        i       Approximation
-------------------------------------
        0       1.000000
        1       3.200000
        2       4.410000
        3       4.804370
        4       7.895877
        5       8.912368
        6       9.914798
        7       10.915101
        8       11.915134
        9       12.915137
        10      13.915137
Exact Value =       9.025013
Run Code Online (Sandbox Code Playgroud)

输出应该是:(忽略空格/标签)

   i Approximation
--------------------------------
   0   1.0000000000
   1   3.2000000000
   2   5.6200000000
   3   7.3946666667
   4   8.3707333333
   5   8.8002026667
   6   8.9576747556
   7   9.0071659835
   8   9.0207760712
   9   9.0241029815
   10   9.0248349018
Exact Value = 9.0250134994
Run Code Online (Sandbox Code Playgroud)

我似乎无法在我的代码中找到问题.我已经看了一些用于阶乘和幂函数的伪代码,没有什么突出的.我的结果仍然是错误的.有什么想法吗?

Jab*_*cky 5

有两个问题:

  1. exponent您不初始化的功能中sum
  2. 你的factorial功能错了.

如果你已经factorial单独测试了这个功能,你至少可以自己找到这个问题.