gpt4 book ai didi

计算 e^x 的 C 程序

转载 作者:行者123 更新时间:2023-11-30 15:01:07 25 4
gpt4 key购买 nike

我正在尝试编写一个 C 程序来评估 e^x,但我不确定我是否走在正确的轨道上。对于较低的 x 值,它似乎可以正常工作,但超过 5 可能会出现太多错误。只是想知道是否有人能看到我的代码哪里出了问题(或者如果我的代码是正确的,是否可能是 PC 无法处理 n 的大值 n 的问题!)。

谢谢:-)

韦德福德

unsigned int counter1 = 1, counter2 = 1, counter3 = 1, num, numFactorial, X;
float e, ex, x;

printf( "%s", "Enter a number: ");
scanf( "%d", &num);

printf( "%s", "Enter a value for x: ");
scanf( "%f", &x);

e = e + 2;
counter3 = num;

while ( counter3 > 1 ) {

counter1 = counter3;
numFactorial = counter3;
X = x;

while( counter1 > 1 ) {
numFactorial = numFactorial * ( counter3 - counter2);
counter1--;
counter2++;
X = X * x;
}
counter2 = 1;
e = e + ( 1 / (float) numFactorial );
ex = ex + X * ( 1 / (float) numFactorial );
counter3--;
}

ex = ex + x + 1;

printf( "e to the nth order of approximation (n = %d) is: %f", num, e);
printf( "\ne^x to the nth order of approximation (n = %d) is: %f", num, ex);

最佳答案

我刚刚尝试了你的代码,当 x=3 时,它最多可以工作到 num=19 (所以扩展中的第 19 阶)。此后,数量就偏离了预期值。那是溢出的问题,你的数字太大了。

如果我理解正确的话,您想要获取 Neper number 的值以及两个级数展开中给定数字 x 到给定阶 (num) 的指数。

然后你就可以计算阶乘数了!在你的代码里面。如果 numfactorial 是无符号整数,则这不适用于大于 15 左右的数字。只是因为数字的表示形式。至少使用双倍。

根据我的经验,当您需要计算阶乘时,如果这就是您想要做的,请使用 Gamma Function ,它位于库“math.h”中,称为 tgamma。如果您查看 Gamma 函数的维基百科页面,您可以使用它来获取整数的阶乘:num! = tgamma(num+1)

关于计算 e^x 的 C 程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41648476/

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