问题描述:公鸡一只5钱,母鸡一只3钱,小鸡三只1钱,问如何用100钱买100只鸡?
分析:1)如果全买公鸡,那么最多买20只,定义变量cock,0 <= cock <= 20;
2)如果全买母鸡,那么最多买33只,定义变量hen,0 <= hen <= 33;
3)如果全买小鸡,则小鸡必须为3的倍数,定义变量chick, 0 <= chick <= 99;
代码:
#include <stdio.h>
int main ()
{
int cock, hen, chick;
for (cock = 0; cock <= 20; cock ++)
for (hen = 0; hen <= 33; hen ++)
for (chick = 0; chick <= 99; chick += 3)
{
if ( (5 * cock + 3 * hen + chick / 3) == 100 )
if ( (chick + hen + cock) == 100)
printf("COCK : %d\tHEN : %d\tCHICK : %d\t\n",cock, hen, chick);
}
return 0;
}
运行结果: