我正在做第一年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;
}
我在代碼中看不到任何因子實現 – m0skit0 2015-02-05 16:37:04
您可以使用[gdb](http://www.gnu.org/software/gdb/)。 – 2015-02-05 16:37:18
「請注意,我認爲* n *在這種情況下意味着階乘。」不,'!'表示階乘因子,您在代碼中省略。 – 2015-02-05 16:39:52