C++递归算法

C++递归算法:我的理解

//递归算法,总结起来具有以下几个特点:
//特点1  它有一个基本部分,即直接满足条件,输出
//特点2  它有一个递归部分,即 通过改变基数(即n),来逐步使得n满足基本部分的条件,从而输出
//特点3  在实现的过程中,它采用了分治法的思想:
//即将整体分割成部分,并总是从最小的部分(基本部分)开始入手(输出),
//其背后的原理在于 当整体递归到部分时,会保留整体的信息,部分满足条件输出的结果会被回溯给整体使用,从而使得整体输出结果。
//特点4  每一步操作,整体都会将部分当作其必要的一个步骤,从而实现整体步骤的完成

//
//例子1: 阶乘 n!
//n != n*(n - 1) != n*n - 1 * (n - 2) != .....
#include <iostream>
using namespace std;
class illegalParameterValue
{
public:
	illegalParameterValue(){};

	illegalParameterValue(int theMessage) :Message(theMessage){}
	int GetMessage(){ return Message; }

private:
	int Message;
};

int factorial(int n)
{
	if (n <= 1)//特点1  它有一个基本部分,即直接满足条件,输出
	{
		throw illegalParameterValue(n);
	}
	else       //特点2  它有一个递归部分
	{
		// 特点4   整体利用部分结果  
		return n*factorial(n - 1);// 特点3 递归部分, 
	}

}

int main0201()
{
	int n = 3;
	try
	{

	int sum = factorial(1);
	}
	catch (illegalParameterValue err)
	{
		cout << "输入阶乘数出错:"  << err.GetMessage() << endl;
	}


	system("pause");
	return 0;
}
//重载<< >>
//在重载输出输入运算符的时候,只能采用全局函数的方式(因为我们不能在ostream和istream类中编写成员函数),这里才是友元函数真正的应用场景。
//对于输出运算符,主要负责打印对象的内容而非控制格式,输出运算符不应该打印换行符;
//对于输入运算符,必须处理可能失败的情况(通常处理输入失败为默认构造函数的形式),而输出运算符不需要。
class Test {
	friend ostream & operator<<(ostream &out, Test &obj);
	friend istream & operator >> (istream &in, Test &obj);
public:
	Test(int a = 0, int b = 0)
	{
		this->a = a;
		this->b = b;
	}
	void display()
	{
		cout << "a:" << a << " b:" << b << endl;
	}
public:


private:
	int a;
	int b;
};
//	cout << t1 << endl;;
ostream & operator<<(ostream &out, Test &obj)
{
	out << obj.a << " " << obj.b;
	return out;
}
istream & operator>>(istream &in, Test &obj)
{
	in >> obj.a >> obj.b;
	if (!in)
	{
		obj = Test();
	}
	return in;
}
int main()
{
	Test t1(1, 2);
	cout << t1 << endl;
	cout << "请输入两个int属性:";
	cin >> t1;
	cout << t1 << endl;;
	cout << "hello world!\n";
	system("pause");
	return 0;
}
#include <iostream>
using namespace std;

class Test
{
	friend ostream& operator << (ostream &out, Test &obj);
	friend istream& operator >> (istream &in, Test &obj);
public:
	Test()
	{
		this->a = 0;
		this->b = 0;
	}
	Test(int a, int b)
	{
		this->a = a;
		this->b = b;
	}
	void display()
	{
		cout << a << " " << b << endl;
	}


private:
	int a;
	int b;
};

ostream& operator << (ostream &out, Test &obj)
{
	out << obj.a << " " << obj.b << endl;
	return out;
}

istream& operator >> (istream &in, Test &obj)
{
	in >> obj.a >> obj.b;
	if (!in)
	{
		obj = Test();
	}
	return in;
}
int main()
{
	Test t1(1, 2);
	cout << t1 << endl;
	//ostream& operator << (ostream &out, Test &t1);
	cout << "请输入两个int属性:";
	cin >> t1;
	//istream& operator >> (istream &out, Test &t1);
	cout << t1 << endl;;
	cout << "hello world!\n";
	system("pause");
	return 0;
}


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值