鸡兔同笼问题我在最初学习c语言时便接触到了,最初的解法便是通过二元一次方程求解。
如下:
#include<stdio.h>
int main()
{
int a, b, x, y;
printf("请输入头的总数:");
scanf("%d", &a);
printf("请输入脚的总数:");
scanf("%d", &b);
y = (b - 2 * a) / 2;
x = (4 * a - b) / 2; //根据a=x+y,b=2*x+4*y得出
printf("一共有鸡%d只,一共有兔%d只", x, y);
return 0;
}
但随着学习的深入,待学到了循环结构后便有了新的解法。
如下:
#include<stdio.h>
int main()
{
int x, y, a, b;
printf("请输入头的总数:");
scanf("%d", &a);
printf("请输入脚的总数:");
scanf("%d", &b);
int is = 1;
for (x = 0; x <= a; x++)
{
y = a - x;
if (x * 2 + 4 * y == b)
{
printf("一共有鸡%d只,一共有兔%d只", x, y);
is = 0;
}
}
if (is == 1)
printf("没有答案");
return 0;
}
通过循环结构不断尝试兔子与鸡的个数,直到达成输入的总只数和总脚数与鸡兔的个数所满足的条件,那么那个值便是答案。
且现在可以判断有无答案,将问题更加完善。