C语言递归解决分鱼问题

Python014

C语言递归解决分鱼问题,第1张

#include <stdio.h>

#include <stdlib.h>

int fish(int n, int x)

/* run this program using the console pauser or add your own getch, system("pause") or input loop */

int main(int argc, char *argv[]) {

int i=0, flag = 0, x

do{

i=i+1

x=i*5+1

if(fish(5,x))//递归判断

{

flag = 1

//flag标识

printf("五个人合伙捕到的鱼总数是%d\n", x)

}

}while(!flag)

return 0

}

int fish(int n, int x)//x表示人数,x表示醒来后剩下的鱼

{

if(x%5==1)

{

if(n==1)

return 1

else

return fish(n-1, (x-1)/5*4)

}

return 0

}//这里递归的作用是作为判断条件

下面代码是我自己写的,看别人代码比较累,所以如果楼主愿意,可以看看下面的代码,我会尽量讲解细致一点。

#include <stdio.h>

//sub(manth,fishleft)参数意义:manth表示第几个人分鱼,fishleft表示他分鱼时获得了多少鱼

//函数的返回结果是第manth个人分鱼时剩余的条数,如manth = 5,fishleft = 1,则表示一共捕获了3906条鱼。

int sub(int manth,int fishleft){

if(manth == 1){

fishleft = (5*fishleft +1)

printf("manth = %d,fishleft = %d\n",manth,fishleft)

return fishleft

}

fishleft = 5*sub(--manth,fishleft)+1

printf("manth = %d,fishleft = %d\n",manth+1,fishleft)

return fishleft

}

int main(void){

int manth = 5

int fishleft = 1

printf("%d\n",sub(5,1))

return 0

} //我得到的结果和楼主所给程序运行结果不一致!楼主可以自己计算,如果最后一个人得到的是1条鱼,则他分鱼时应该剩余6条,manth = 2时应该剩余6*5+1 = 31条,manth = 3时,应该剩余31*5+1条,最后manth= 5,也就是分鱼开始的时候,应该剩余3906条鱼。

//楼主可以用自己的程序测试,当调用sub(2)时得到的是21,而不是31,就能证明该程序应该是用问题的。