2017-10-11 101 views
-3

該代碼是指通過將逆階乘計算數學常數Ë:的爲什麼我的計算給出'inf'而不是數字?

#include <stdio.h> 
void main() 
{ 
    int i, n,a; 
    float result=1; 
    float sum; 
    a=1; 
    sum=0; 
    printf("Enter a number:\n"); 
    scanf("%d",&n); 

    for (i=0;i<=n-1;i++) 
    { 
     result=result*i; 
     sum = a + (i/result); 

    } 

    printf("%.2f is the answer\n",sum); 

}

而不是給Ë的值時,它產生inf is the answer

爲什麼我會得到inf而不是2.78

+2

的[返回節目INF?]可能的複製(https://stackoverflow.com/questions/25577846/program-returning-inf) – Gianlucca

+0

參閱http:/ /floating-point-gui.de/ –

+6

第一次通過循環乘以'result'0(因爲'i'被初始化爲0),返回0.所以'result'將總是等於0.所以,結果「(下一行是'sum = a +(i/result);')等於無窮大。 – AntonH

回答

3

您提到的錯誤源於您除以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; 
} 
相關問題