递归分鱼问题
尽管有代码,但我还是不能理解,请各位大神详细解释。谢谢!!!!:cry题目:abcde五人打渔,打完睡觉,a先醒来,扔掉1条鱼,把剩下的均分成5分,拿一份走了;b再醒来,也扔掉1条,把剩下的均分成5份,拿一份走了;然后cde都按上面的方法取鱼。问他们一共打了多少条鱼?
代码:
<blockquote>#include<stdio.h>
#include<stdio.h>
int sub(int n) /*定义函数递归求鱼的总数*/
{
if (n == 1) /*当n等于1时递归结束*/
{
static int i = 0;
do
{
i++;
}
while (i % 5 != 0);
return (i + 1); /*5人平分后多出一条*/
}
else
{
int t;
do
{
t = sub(n - 1);
}
while (t % 4 != 0);
return (t / 4 * 5+1);
}
}
main()
{
int total;
total=sub(5); /*调用递归函数*/
printf("the total number of fish is %d\n",total);
return 0;
}
你这题是错的。题应该是先均分成5份,然后把多余的一条扔掉。这样才能算出来。
<p>int fun(int fishCount,int peopleCount)
{
//最后函数的出口
if (peopleCount == 0)
{
return 1;
}
if(fishCount%PEOPLE_COUNT ==1)
{
fishCount = fishCount - (fishCount-1)/PEOPLE_COUNT - 1;
fun(fishCount,peopleCount-1);
}
else
{
return 0;
}
}
int _tmain(int argc, _TCHAR* argv[])
{
int i;
for(i=6;i<100000;i++)
{
if (fun(i,PEOPLE_COUNT))
{
printf("至少得%d条鱼",i);
break;
}
}
return 0;
}</p><p>你看看这个能不能懂!
</p> 我那个代码是标准答案,用的是递归的思想,但方法过于巧妙,我看不透……所以我想请高手帮忙解读一下 看看那
页:
[1]