阶乘递归

Factorial Recursive

我正在尝试编写一种算法来使用递归函数计算数字的阶乘。

这是我的代码:

#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 函数中,您正在等待另一个不需要的输入。从 factorial 方法中删除此 cin >> n;

其他问题中没有问到的点:

  • 阶乘增长得非常快,使用 int 你很快就会溢出。您可以考虑改用 64 位 long long
  • conio.h 不标准,应该避免。
  • 在全局范围内调用 using namespace std 非常糟糕。

您的程序没有做任何事情。它正在做你不期望的事情。 cin >> n 应该在主函数中,而不是在阶乘函数中。

它实际做的是将每个新数字作为对阶乘的函数调用放在堆栈上。每次 re-input 您都在更改阶乘项。例如,您输入“4”,然后是“6”,然后是“8”……堆栈中的阶乘 (8) 位于顶部,然后是阶乘 (6),然后是阶乘 (4)。最后你必须输入“1”,这样你的程序才会结束。

不要在阶乘方法中要求用户输入。改为这样做

int factorial(int n) {
    if (n == 0 || n == 1)
        return 1;
    return n*factorial(n - 1);
}
int main() {
    int n;
    cout<<"Enter a number:";
    cin >> n;
    cout << factorial(n);
    return 0;
}

你初始化了

n=0;

它不会在 main fn 中接受您的输入并始终使用

调用 factorial fn
factorial(0);

并从事实 fn 中删除 cin>>n 并执行类似

的操作
int factorial(int n)
{ if (n == 0)
   return 1;
   return n*factorial(n-1);
}

main()
 {
  cin>>n;
  cout<<factorial(n);
  }

对于大阶乘,使用浮点数,它支持对包含大量 0 的数字进行指数表示法。

此外,递归所做的是将数字阶乘中传递的数字推入堆栈,然后 return 一旦函数调用最终 returns,即它为 1 时,它们将被推入栈中。

出于说明目的,请尝试此程序。

// ConsoleApplication1.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"
#include <iostream>
using std::cout;
using std::endl;
using std::cin;

int factorialtimes2(int n) {
    if (n <= 1)
        return 1;
    return n*factorialtimes2(n - 1)*2;
}

int main()
{
    cout << factorialtimes2(5) << endl;
    cout << 5 * (4 * 2)*(3 * 2)*(2 * 2)*(1 * 2) << endl;
    return 0;
}