2017-08-27 46 views
-5
#include<iostream> 
using namespace std; 

int main() 
{ 
    int fact; 
    for(int i=1; i<=fact; i++) 
    { 
    fact = fact*i; 
    } 
    cout<<fact; 
} 

输出:垃圾值。阶乘使用forree循环给出垃圾值

请任何人告诉我为什么使用增量for循环给我这个,但不是循环递减。

+4

'fact'心不是初始化这意味着它的值是不确定的。 –

+1

'fact'的初始值是多少? –

+4

当你解决这个问题时,考虑使用一个不断增加的变量作为循环中的限制。 –

回答

3

你可以做两件事情,

1)如果您希望自己的代码,你必须初始化YOUT值事实与价值1:

int fact = 1; 

2)有一个很简单的一个班轮这“事实” -stuff。如果我在某个时候需要它,我经常自己使用它。

int factorial(int n) 
{ 
    return (n == 1 || n == 0) ? 1 : factorial(n - 1) * n; 
} 
2
#include<iostream> 
using namespace std; 
int main() 
{ 
     int fact,z=1; 
     cin>>fact; 
     for(int i=2; i<=fact; i++) 
     { 
     z= z*i; //use another variable using fact here will lead to a possible infinite loop 
     } 
     cout<<z<<"\n"; 
}