今有鸡兔同笼,上有三十五头,下有九十四足,问鸡兔几何?
#include <iostream>
using namespace std;
int scanning(int head, int foot, int* chicken, int* rabbit);
int main()
{
int chicken, rabbit,head, foot;
cout << "穷举法求解鸡兔同笼问题" << endl;
cout << "请输入头数" << endl;
cin >> head;
cout << "请输入脚数" << endl;
cin >> foot;
if ((scanning(head, foot, &chicken, &rabbit))== 1)
{
cout << "鸡有:" << chicken << "只" << endl;
cout << "兔有:" << rabbit << "只" << endl;
}
else
{
cout << "无解" << endl;
}
return 0;
}
int scanning(int head, int foot, int* chicken, int* rabbit)
{
int re, i, j;
re = 0;
for (i = 0; i <= head; i++)
{
j = head - i;//当i为0时一共有j头,i+j=head;
if (i * 2 + j * 4 == foot)
{
re = 1;
*chicken = i;//如果条件满足,那就把i给鸡
*rabbit = j;//如果条件满足,那就把j给兔
}
}
return re;
}
换一种写法(双重循环)
//从0开始循环,万一全是兔子或者全是鸡呢对吧
for (i = 0; i <= head; i++)
{
for (j = 0; j <= foot; j++)
{
if ((i + j == head) && (i * 2 + j * 4 == foot))
{
re = 1;//标记
*chicken = i;
*rabbit = j;
}
}
}
您想请我喝瓶水吗?建议打赏价格在2元一下。