2015-02-05 46 views
0

我正在做第一年C班的作业,我们在教科书的循环部分。我已经学会了几种语言,但我相信我做错了某种方式,因为我没有得到正确的输出。我相信我需要使用循环来做这个问题(所以没有额外的数学库)。通常我会使用调试器,但我使用崇高的文本和命令提示符编程C,所以我不认为这是可能的。我们还没有经历过方法/功能/无论C使用什么,所以我的解决方案不能使用这些东西。使用基于用户输入的循环近似e

仅使用C89是优选的。

这里是这样的问题:

数学常数Ë的值可以被表达为一个 无穷级数: ë = 1 + 1/1! + 1/2! + 1/3! + ... 通过计算1 + 1/1的值,编写一个近似于e的程序! + 1/2! + 1/3! + ... + 1/n! 其中n是用户输入的整数。

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

我正在检查我的输出与这个西格玛计算器的输出,并在计算器的输出中加入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

我在代码中看不到任何因子实现 – m0skit0 2015-02-05 16:37:04

+0

您可以使用[gdb](http://www.gnu.org/software/gdb/)。 – 2015-02-05 16:37:18

+0

“请注意,我认为* n *在这种情况下意味着阶乘。”不,'!'表示阶乘因子,您在代码中省略。 – 2015-02-05 16:39:52

回答

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) + ... 
} 
+0

根据问题的详细信息,不幸的是我不能使用功能:( – 2015-02-05 16:45:43

+0

我编辑了答案,所以现在没有功能 – farukdgn 2015-02-05 16:47:38

+0

我试着用你的解决方案,我仍然得到不正确的输出...当我输入2,我的输出是“e等于2.000000”,当正确的输出(我相信)应该是2.500000。 – 2015-02-05 16:58:05

1

没有你的代码只是让资金超过我在中山医科大学的[1,I]的1/J。 (1/1 + 1/2)+(1/1 + 1/2 + 1/3)+ ...而不是1/1 +(1/1 * 1/2) +(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; 

} 
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

+0

感谢您的帮助,您和farukdgn的回答对我的帮助最大,但我只能接受一个回答,抱歉!请尽快回复:) – 2015-02-05 17:06:15

2

循环可以简单到像这样的:需要

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

没有嵌套循环。 Here是一个工作版本。

+1

'我<输入“或”我<=输入“? – 2015-02-05 16:48:57

+0

是的,应该是'<=',但是O.P.发布条件为'<'所以O.P.想要循环'n-1'次。 – 2015-02-05 16:52:10