【反思】
1.可以利用递归来进行判断,返回逻辑值1或0。
2.递归结束的条件和返回的值要慎重斟酌,题目没有明确说明已知信息,自己不能瞎编。
int Fun(int n)
{
if (n == 5)
return 6;//错在这个地方,最后一个人剩下的鱼不是6条,题目没有明说时不能瞎编
else
return 5 * Fun(n + 1) + 1;
}
3.出现“至少”的字样,可能需要利用循环条件为“1”的无限循环寻找可能的值。
【代码】
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <ctype.h>
#include <string.h>
#define maxSize 100
int Fish(int x,int n)
{
if (x %5 == 1 && n == 5)//易错点:递归结束条件,如果第5个人能够在扔掉一条的情况下将鱼平分成5分说明这个数正确
return 1;
else if (x % 5 == 1)
{
int y = (x - 1) / 5;
return Fish(x - 1 - y, n + 1);//扔掉一条,自己再拿走一条,留给其他人的就只有x-1-y条
}
else
return 0;
}
int main()
{
int i = 2;
while (1)
{
if (Fish(i,1))
{
printf("%d", i);
break;
}
++i;
}
return 0;
}
【结果】
【版本2】
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <string.h>
#include <ctype.h>
#define maxSize 100
int Catch(int n, int p)
{
if (p == 1 && n % 5 == 1)
{
return 1;
}
else if (n % 5 != 1)//本题极易做错的地方就在于此处,在分鱼过程中一旦发现无法正确分鱼的时候就要截断分鱼的过程,而不是继续分下去
return 0;
else
{
int x = (n - 1) / 5;
n = n - x - 1;
Catch(n, p - 1);
}
}
int main()
{
int n = 1;
while (1)
{
if (Catch(n, 5))
break;
n++;
}
printf("%d", n);
return 0;
}