我正在尝试编写一种算法来使用递归函数计算数字的阶乘。
这是我的代码:
#include <stdio.h>
#include <conio.h>
#include <iostream>
using namespace std;
int factorial(int n) {
cin >> n;
if (n == 1)
return 1;
return n*factorial(n - 1);
}
int main() {
int n = 0;
cout<<"Enter a number:";
cout << factorial(n);
return 0;
}
它什么也没做,我不知道为什么,它只让我给出数字,但它不计算。
在 - 的里面factorial
函数您正在等待另一个不需要的输入。删除这个cin >> n;
从里面factorial
method.
问题中没有提出的其他一些要点:
- 阶乘增长非常快并且通过使用
int
你很快就会溢出。您可以考虑使用64位long long
反而。
-
conio.h
不是标准的,应该避免。
- Calling
using namespace std
在全球范围内是非常糟糕的。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)