gpt4 book ai didi

c - 用C语言查找 'e'的近似值

转载 作者:行者123 更新时间:2023-12-02 09:12:10 24 4
gpt4 key购买 nike

我正在尝试使用C程序查找'e'的近似值。我正进入(状态
不管我输入n的值是什么,e的值都是真实的。请让我
在我的代码中找到错误。

#include <stdio.h>

int f;
int k;

int factorial (int f);

int main () {
int n,i;

int e = 1;

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

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

printf("The value of e is %d",e);

return(0);
}

int factorial (int f) {
for (k = 1; k <= f; k++) {
f = f*k;
}

return(p);
}

最佳答案

您有一些错误。您正在int变量中添加浮点值!请阅读以下代码的注释:

int k; // remove f

int factorial (int f);

int main () {

int n,i;

float e=1; // take e as float/double, not int

printf("Enter the value of n:");

scanf("%d",&n);

for (i=1 ; i<=n ; i++) {

e=e+(1.0/factorial(i)); // take 1.0 (floating value) instead of 1 (integer value)
}

printf("The value of e is %f",e);

return(0);
}

int factorial (int f) {
int total=1; // initialize total with 1
for (k=1 ; k<=f ; k++) {

total=total*k; // here is a big mistake in your code. You incremented value of f in every iteration. Try to print value of f after every iteration to find your error.
}

return(total);
}

关于c - 用C语言查找 'e'的近似值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50898084/

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