阶乘使用循环递增给出垃圾值

factorial using increement for loop gives garbage value

本文关键字:循环 阶乘      更新时间:2023-10-16
#include<iostream>
using namespace std;
int main()
{
int fact;
for(int i=1; i<=fact; i++)
{
fact = fact*i;
}
cout<<fact;
}

输出:垃圾值。

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

你可以做两件事,

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

int fact = 1;

2)对于这个"事实"的东西,有一个非常简单的衬里。如果我在某些时候需要它,我经常自己使用它。

int factorial(int n)
{
return (n == 1 || n == 0) ? 1 : factorial(n - 1) * n;
}
#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";
}