因子递归

时间:2018-03-11 18:08:54

标签: c++ recursion factorial

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

这是我的代码:

#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;
}

它什么都不做,我不知道为什么,它只允许我给出数字,但它没有计算。

5 个答案:

答案 0 :(得分:2)

factorial函数内部,您正在等待另一个不需要的输入。从cin >> n;方法中删除此factorial

问题中未提及的其他一些观点:

  • 因子增长非常快,使用int你很快就会溢出。您可以考虑使用64位long long代替。
  • conio.h不是标准的,应该避免使用。
  • 在全球范围内调用using namespace std非常糟糕。

答案 1 :(得分:0)

你的程序什么都不做。它正在做你不想要的事情。 cin&gt;&gt; n应该在main函数中,而不是在factorial函数中。

它实际上做的是将每个新数字作为函数调用放在堆栈上的factorial。每当您重新输入时,您都需要更改阶乘的条款。例如,您输入&#34; 4&#34;,然后输入&#34; 6&#34;,然后输入&#34; 8&#34; ...您在堆栈上的内容是factorial(8)on顶部,然后是阶乘(6),然后是阶乘(4)。最终你必须输入&#34; 1&#34;这样你的程序就会结束。

答案 2 :(得分:0)

请勿在factorial方法中询问用户输入。这样做

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

答案 3 :(得分:0)

你初始化了

n=0;

在主fn中没有从你那里获取输入并且总是用

调用factorial fn
factorial(0);

并从事实fn中删除cin&gt;&gt; n并执行类似

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

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

答案 4 :(得分:0)

对于较大的阶乘,请使用浮点数,该浮点数对0很大的数字都支持指数表示法。

此外,递归操作是将通过数字阶乘传递的数字压入堆栈,然后在函数调用最终返回(即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;
}
相关问题