遞歸算法實現賣鴨子

        問題重述:

1.一個人趕着鴨子去每個村莊賣,每經過一個村子賣去所趕鴨子的一半又一隻。這樣他經過了七個村子後還剩兩隻鴨子,問他出發時共趕多少隻鴨子?經過每個村子賣出多少隻鴨子?

代碼:

題目分析:

   設在經過n個村子時有xn只鴨子,根據題意可以得到如下遞推公式:

   則在第n+1個村子時有xn-xn2+1=xn2-1只鴨子,即

    xn+1=xn2-1,所以xn-1=xn+1×2

   在經過第7個村子書還剩下2只鴨子,即

   x7=2

算法構造:

   根據上述公式可以看出:

   函數出口爲:   x7=2

   函數體爲:xn-1=xn+1×2

用最後的鴨子數倒推上一步的鴨子數,再以此類推,在經過最後一個村子時只剩下2兩隻鴨子,每遞歸一次經過的村次數就減少一個,直到最後爲0即跳出函數

算法實現:

#include<iostream>
using namespace std;

/*
Auther:Qiaoxue Zheng
Date:2018/11/15
Discribtion:To calculate how many duck the man have
when he sold hal of ducks and one more acrosss a village
and he only have two ducks when across 7 villages
*/

/*
Function:get the number of ducks when he passed  count villages
Parameter:
	count: the number of villages
*/
int saleDuck(int count) {
	
	if (count == 0) {//exit,only two ducks left at last
		return 2;
	}
	else {//body,get the number of ducks at the last time
		count--;
		return (saleDuck(count) + 1) * 2;
	}
}

//Main function
int main() {

	int acount_duck = 0;
	int acount_village = 7;
	acount_duck = saleDuck(acount_village);
	cout <<"一共趕了"<<acount_duck<<"只鴨子"<<endl;

	int all = 0;//the number of all ducks
	int sale = 0;//the number of sold ducks
	int rest = 0;//the number of rest ducks

	//get the numbe of ducks when the man passed every village
	for (int count = 7; count >= 1; count--) {
		all = saleDuck(count);
		sale = all / 2 + 1;
		rest = all - sale;
		cout << "經過第" << 8 - count << "個村莊時賣了" << sale << "只鴨子,還剩" << rest << "只鴨子" << endl;

	}

	system("pause");
	return 0;
}

運行結果:

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章