2015-02-05 43 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