阶乘递归 [英] Factorial Recursive
本文介绍了阶乘递归的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试编写一种算法,以使用递归函数来计算数字的阶乘.
I'm trying to write an algorithm to calculate the factorial of a number using recursive function.
这是我的代码:
#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;
}
它什么都不做,我也不知道为什么,它只允许我给出数字,但它不是在计算.
It does nothing and I don't know why, it only lets me to give the number, but it's not calculating.
推荐答案
在factorial
函数内部,您正在等待不需要的其他输入.从factorial
方法内部删除此cin >> n;
.
Inside the factorial
function you are waiting for another input which is not needed. Remove this cin >> n;
from inside the factorial
method.
问题中没有问到的其他几点:
Some other points which are not asked in the question:
- 工厂发展非常迅速,通过使用
int
,您很快就会溢出.您可以考虑改用64位long long
. -
conio.h
不是标准的,应避免使用. - 在全局范围内调用
using namespace std
是非常糟糕的.
- Factorials grow very fast and by using
int
you will quickly get an overflow. You may consider to use 64 bitlong long
instead. conio.h
is not standard and should be avoided.- Calling
using namespace std
in global scope is very bad.
这篇关于阶乘递归的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文