gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-29 15:57:01 25 4
gpt4 key购买 nike

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

f(x, n) = e^x = the sum of i=0 up to 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

我正在使用迭代而不是递归。我当前使用 ./aproroximation 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

输出应该是:(忽略空格/制表符)

   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

我似乎无法在我的代码中找到问题。我看过一些阶乘函数和幂函数的伪代码,但没有什么特别之处。我的结果仍然是错误的。有什么想法吗?

最佳答案

有两个问题:

  1. exponent 函数中,您没有初始化 sum
  2. 您的factorial 函数是错误的。

如果您单独测试过 factorial 函数,您自己至少会很容易地发现这个问题。

关于c - 如何修复我的 e^x 近似 C 程序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42349953/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com