使用基于用户输入的循环来近似e

时间:2015-02-05 16:35:01

标签: c

我在第一年的C课上完成作业,我们在教科书的循环部分。我已经学会了一些语言,但我相信我在某种程度上做错了,因为我没有得到正确的输出。我相信我需要使用循环来做这个问题(所以没有额外的数学库)。通常我会使用调试器,但我使用sublime文本和命令提示符编程C,所以我不认为这是可能的。我们还没有完成方法/功能/ C使用,所以我的解决方案不能使用那些东西。

首选仅使用C89。

以下是问题:

  

数学常数 e 的值可表示为a   无限系列:    e = 1 + 1/1! + 1/2! + 1/3! + ...   通过计算1 + 1/1的值来编写一个近似 e 的程序! + 1/2! + 1/3! + ... + 1 / n !   其中 n 是用户输入的整数。

请注意,我相信在这种情况下意味着阶乘。

我检查我的输出与此sigma计算器的输出,只需在计算器的输出中加1,以检查我的结果是否正确。

http://www.mathsisfun.com/numbers/sigma-calculator.html

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

int main(void)
{
    float e = 1;/* Start off as 1 since the equation adds 1 anyways */
    int input, i, j;

    /* Ask the user for the value that they want to use, and store it in a variable */
    printf("Enter an integer to use to approximate: ");
    scanf("%d", &input);

    for (i = 1; i < input; i++)
    {
        /* This inside loop is for the factorial, where j goes through all of the factorials for each i */
        for(j = i; j > 0; j--)
        {
            e += (1/(float)j);
        }

    }

    printf("e equals %f\n", e);
    return 0;
}

4 个答案:

答案 0 :(得分:4)

循环应该是这样的:

for(i=1; i<=input; i++)
{
    int result = 1;
    for(int j=1; j<=i; j++)
    {
        result = result * j;
    }
    //now the "result" is the factorial of i
    e += 1 / (float)result; // 1/factorial(1) + 1/factorial(2) + ...
}

答案 1 :(得分:2)

你在因子计算中没有做正确的事情。当你应该倍增时,你正在总结。你的内循环可能看起来像这样:

    /* This inside loop is for the factorial, where j goes through all of the factorials for each i */
    float inverse_factorial_i = 1;
    for(j = i; j > 0; j--)
    {
        inverse_factorial_i *= (1/(float)j);
    }

然后

e += inverse_factorial_i

答案 2 :(得分:2)

循环可以很简单:

int fact = 1 ;
for(int i = 1; i < input; ++i)
{
    fact *= i ;
    e += (1.0f/(float)fact);
}

不需要嵌套循环。 Here是一个有效的版本。

答案 3 :(得分:1)

没有你的代码在1 / j的[1,i]中对j的总和超过i。 所以你计算1/1 +(1/1 + 1/2)+(1/1 + 1/2 + 1/3)+ ...而不是1/1 +(1/1 * 1/2)+ (1/1 * 1/2 * 1/3)+ ...

那应该是这样的:

for (i = 1; i < input; i++)
{
    float inversefact = 1;
    for(j = i; j > 0; j--)
    {
        inversefact *= (1/(float)j);
    }
    e += inversefact;

}