简单谈谈C++ 递归的思想实现以及和循环的关系
作者: 来源: 添加时间:2006-5-24 13:33:26下面就是递归(请注意了,这种做法不推荐!! 我只是为了说明问题才这么写的。)
/*using Turboc2*/
int a=0;
int account(int);
main()
{
account(100);
printf("%d",a);
}
int account(int i)
{
if(i==1) return 1; /*停止条件*/
else
return (n+f(n-1)); /*此句有问题*/
}
在C/C++的问题中,我曾经回答过这样的一个问题:
若一头小母牛,从出生起第四个年头开始每年生一头母牛,按此规律,第n年时有多少头母牛? 请问如何用递归涵数求此问题?
先写出函数表达式:f(n)=f(n-1)+f(n-3)
为什么f(n)=f(n-1)+f(n-3)呢,请看:
f(n)-f(n-1)=f(n-3)
因为第n年要比n-1年多的牛,都是大于三岁的牛生的小牛,而f(n-3)正是那些在n年大于三岁的牛,然后它们在第n年生下相同数量的小牛。(请用BorlandC++3.1或其他C++编译器)
#include<iostream.h>
#include<conio.h>
int cattle(int,int);
void main()
{
int ct,n;
cout<<"Please input the original cattle number:"<<endl; /*输入起始牛的数量*/
cin>>ct;
cout<<"Input how many years it past:"<<endl;
cin>>n;
cout<<"You have "<<cattle(ct,n)<<" cattle now!"<<endl;
getch();
}
int cattle(int ct,int n)
{
if(n<4) return (ct); /*停止条件*/
else
return (cattle(ct,n-1)+cattle(ct,n-3)); /*实现递归*/
}
怎么样,很简单吧。 会用循环求解吗?
递归在实际的编程中并不常用,但是在某些情况下,它是非常强有力而漂亮的工具。掌握它的原理时会十分有用的。
第 2 页,共 2 页 [1] [2]
站内搜索