问题
I'm trying to write an algorithm to calculate the factorial of a number using recursive function.
This is my code :
#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.
回答1:
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:
- 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.
回答2:
Your program isn't doing nothing. It is doing what you do not expect. cin >> n should be in the main function, not in the factorial function.
What it is actually doing is placing each new number as a function call to factorial on the stack. Every time you re-input you're changing the terms of the factorial. For example, you input "4", and then "6", and then "8"... what you have on the stack is factorial(8) on top, then factorial(6), then factorial(4). Eventually you'll have to input "1" so that your program will end.
回答3:
Do not ask for user input inside factorial method. Do this instead
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;
}
回答4:
you initialised
n=0;
which doesn't taking input from you in main fn and calling factorial fn always with
factorial(0);
and also remove that cin>>n from fact fn and do something like
int factorial(int n)
{ if (n == 0)
return 1;
return n*factorial(n-1);
}
main()
{
cin>>n;
cout<<factorial(n);
}
回答5:
For large factorials, use floating point which supports exponential notation for numbers with a lot of 0s.
Also, what recursion does is push the numbers passed in number factorials to the stack and then return them once a function call finally returns, which is when it is 1.
For illustrative purposes, try this program.
// 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;
}
来源:https://stackoverflow.com/questions/49223362/factorial-recursive