使用increement for循环的阶乘给出了垃圾值

时间:2017-08-27 13:52:44

标签: c++

#include<iostream>
using namespace std;

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

输出:垃圾值。

请有人告诉我为什么使用increment for循环给我这个但不减少循环。

2 个答案:

答案 0 :(得分:3)

你可以做两件事,

1)如果你想要自己的代码,你必须用值1初始化你的值事实:

int fact = 1;

2)这个“事实”的材料有一个非常简单的衬里。如果我在某些时候需要它,我经常自己使用它。

int factorial(int n)
{
  return (n == 1 || n == 0) ? 1 : factorial(n - 1) * n;
}

答案 1 :(得分: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";
}