您提到的錯誤源於您除以0
這一事實。
你說你正在努力尋找階乘的總和,但你沒有
sum = 1 + 0/0
sum = 1 + 1/0
sum = 1 + 2/0
...
sum = 1 + n/0
代替
sum = 0! + 1! + 2! + ... + n!
錯誤的數量是驚人的!您不執行總和,您爲每個不應該有的項目引入一個因子,而是使用因子的替代因子而不是因子,您添加了1
而不應該有任何因子,並且您錯誤地計算了因子因爲您製作的0!
等於0
而不是1
。
替換
result=result*i;
sum = a + (i/result);
與
if (i)
result=result*i;
sum = sum + result;
一種更簡單的解決方案是種子中的變量與所述第一項,然後環與所述第二開始。以下是解決方案,使用更好的變量名:
int N;
int n;
int n_fact = 1;
int sum = 1;
printf("Enter the number of terms: \n");
scanf("%d", &N);
for (n=1; n<N; ++n) {
n_fact *= n;
sum += n_fact;
}
[我本來以爲你嘗試計算Ë。如果實際情況可能如此,我將在此留下原始答案。]
您提到的錯誤源於您將被除以0
這一事實。
你似乎是試圖接近è,但你沒有
e = 1 + 0/0
e = 1 + 1/0
e = 1 + 2/0
...
e = 1 + n/0
,而不是
e = 1/(0!) + 1/(1!) + 1/(2!) + ... + 1/(n!)
你犯了不少的錯誤!您不執行總和,您爲每個不應該有的項目引入一個因子,您在應該不存在任何項目的位置添加了1
,並且因爲您使0!
等於0
而不是1
而錯誤計算因子。
替換
result=result*i;
sum = a + (i/result);
與
if (i)
result=result*i;
sum = sum + (1/result);
一種更簡單的解決方案是種子中的變量與所述第一項,然後環與所述第二開始。以下是解決方案,使用更好的變量名:
int N;
int n;
int n_fact = 1;
float e = 1;
printf("Enter the number of terms: \n");
scanf("%d", &N);
for (n=1; n<N; ++n) {
n_fact *= n;
e += 1/n_fact;
}
的[返回節目INF?]可能的複製(https://stackoverflow.com/questions/25577846/program-returning-inf) – Gianlucca
參閱http:/ /floating-point-gui.de/ –
第一次通過循環乘以'result'0(因爲'i'被初始化爲0),返回0.所以'result'將總是等於0.所以,結果「(下一行是'sum = a +(i/result);')等於無窮大。 – AntonH