【C++】递归练习

1.递归求阶乘

代码:

#include
using namespace std;

int main()
{
	int jiecheng(int a);
	int n;
	cin >> n;
	if (n == 0)
	{
		cout << 1 << endl;
	}
	else
	cout << jiecheng(n) << endl;
	return 0;
}

int jiecheng(int a)
{
	if (a == 1)
	{
		return 1;
	}
	else 
	{
		while (a > 0)
		{
			return a*jiecheng(a - 1);
		}
	}
}

结果:

【C++】递归练习_第1张图片

 

代码二:

#include"stdafx.h"
#include
using namespace std;

int main()
{
	int jiecheng(int a);
	
	int n;
	cout << "Please input a number: " << endl;
	cin >> n;
	int result;
	result = jiecheng(n);
	cout << "The result is: " << result << endl;
	return 0;
}

int jiecheng(int a)
{
	int n;
	n = a;
	if (n > 1)
		return n * jiecheng(n - 1);
	else
		return 1;
}

结果:

【C++】递归练习_第2张图片

你可能感兴趣的:(C++学习)