gpt4 book ai didi

用于计算 e 值的 C 程序

转载 作者:行者123 更新时间:2023-11-30 19:51:13 24 4
gpt4 key购买 nike

我被分配了一个硬件,要求我通过使用该系列来计算e的值:

1 + 1/1! + 1/2! + ...1/n!

必须计算e的值,直到达到n的值(由用户输入)。此外,必须计算 1/n! 的值,直到其值小于 epsilon(也由用户输入)。

我编写了代码,但编译器告诉我一些错误,例如关系比较、使用“;”等等。有人可以帮我解决这个错误吗?先感谢您。

下面是我的代码:

#include<stdio.h>
int factorial (int i)
{
if (i==0)
return 1;
else
return i*factorial(i-1);
}

int main(void) {

int i,n;
float e,ep;

printf("what is the value of epsilon: ");
scanf("%f",&ep);

printf("what is the value of n: ");
scanf("%d",&n);

for (i=1; i<=n, i++)
e= 1+1/factorial(i);

for(1/fatorial(i)<=ep)
printf("The value of e for the entered value of epsilon and n:%f",e);

return 0;
}

最佳答案

为了获得更高的精度,我会使用double而不是float

for (i=1; i<=n, i++)
e= 1+1/factorial(i);

这是错误的,您没有添加到e,您总是分配最后一个系列的值,始终为 0(i = 1 除外)。所以你的e会始终为 1。

factorial 是一个返回 int 的函数。 int 除以 intint 而在 C 中任何 1/x(对于 x> 1,x 整数)都是 0。你用1.0 或将至少一个参数转换为 double (或 float 如果您是使用 float ):

double e = 1; // initializing e

for(i = 1; i <= n; ++i)
e += 1.0/factorial(i);

Also, the value of 1/n! must be calculated until it's value is smaller than epsilon, also entered by the user.

我不明白这意味着什么,如果n是用户给出的固定值,你一直在计算什么?这真的是练习所说的吗?

我的解释是:如果通过n|e_real - e_calculated| > epsilon,继续递增n,否则停止。那将是

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

uint64_t factorial (uint64_t i)
{
if (i==0)
return 1;
else
return i*factorial(i-1);
}

int main(void)
{
int n;
double e = 1;
double epsilon;

printf("what is the value of epsilon: ");
scanf("%lf", &epsilon);

printf("what is the value of n: ");
scanf("%d",&n);

int i = 1;
while(1)
{
e += 1.0/factorial(i++);

if(i >= n && (fabs(e - M_E) < epsilon))
break;
}

printf("e: %.20lf, calculated e: %.20lf, error: %.20lf, steps: %d\n", M_E, e, fabs(e-M_E), i);

return 0;
}

注意:如果您使用的是 GCC,则必须使用 -lm 选项进行编译:

$ gcc e.c -oe -lm

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

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