#include
#include
using namespace std;
int fact(int n)
{
int num=1;
stack S;
L:
if(n>0)
{
S.push(n);
n=n-1;
goto L;
M:
num *= S.top();
}
if(!S.empty())
{
S.pop();
goto M;
}
return num;
}
int main()
{
int n;
cin>>n;
cout<<fact(n)<<endl;
}
我觉得作者做的是一个类似于阶乘的函数,并利用stack来实现,而且如果不用goto语句的话,还是一个很优美、很简洁的代码。
下面我用while代替goto语句,重新了编排一些语句,大概可以更清晰一点:
#include <iostream>
#include <stack>
using namespace std;
int fact(int n)
{
int num=1;
stack<int> S;
while(n>0)
{
S.push(n);
n--;
}
while(!S.empty())
{
num *= S.top();
S.pop();
}
return num;
}
int main()
{
int n;
cin >> n;
cout << fact(n) <<endl;
}
实际上这个程序第一次是被Windows10系统强制关闭的,可能是因为栈越界。现在改为循环语句的模式,虽然效率不高,但是至少可以输出了。
最后,祝愿题主学业有成!
(码字不易,望采纳!)