How to solve problems with recursion method
Problem:
- A recursive function is used to calculate the factorial of the n value of the user input and to output it.
Problems encountered
1, recursive understanding is not deep enough, first of all to think of what conditions to meet with recursion, under what conditions to meet the end of recursion and return a value.
2, the most important is the logic of recursion, such as the following code
Experiment Nine (1). CPP: Defines the entry point of the console application. #include "stdafx.h" #include <iostream>using namespace std;int factorial (int n) {int f=1;if (n > 1) {f = factorial (n-1) *n;} Elsereturn F;} int main () {int n;cin >> n;cout << factorial (n); return 0;}
It seems that the value of F will be re-assigned to 1 at each recursive time, and then the result is not correct, but the logic is
When N=1 is not satisfied with the condition of recursion, the return value is 1 and the result is correct
When n=2 satisfies the condition but does not recursively run only once so that the return value is 2, the result is correct
When the n=3 is recursive, that is, F = factorial (2), and because factorial (2) =2 so the final result is 6 is correct, and so on, and so on is the right one after the other
This is the way to push backwards from behind.
Recursive method problems in C + +