题目
今有鸡兔同笼,上有35头,下有94足,问鸡、兔各有几只?
分析
这个问题需要计算鸡的数量和兔的数量,可知均为0~35之间,最直接的思路就是使用穷举法逐个判断是否符合,从而搜索答案~
代码
#include <iostream>
#include <cstdlib>
using namespace std;
//穷举算法,对鸡兔的数量用引用传递,若存在结果返回true,否则返回false
bool QiongJu(int heads, int foots, int &chicken, int &rabbit)
{
bool ret = false;
int c, r;
for (int c = 0; c < heads; c++)
{
r = heads - c;
if ((2 * c + 4 * r) == foots)
{
ret = true;
chicken = c;
rabbit = r;
}//if
}//for
return ret;
}
int main()
{
int chicken, rabbit, heads, foots;
cout<< "请输入头足的数量:\n";
while (cin >> heads >> foots)
{
bool ret = QiongJu(heads, foots, chicken, rabbit);
if (ret)
{
cout << "鸡有:" << chicken << "只,兔有:" << rabbit << "只。" << endl;
}
else{
cout << "无解!" << endl;
}
}//while
system("pause");
return 0;
}