C++ 鸡兔同笼问题求解程序
#include
using namespace std;
int main() { int heads, legs, chickens, rabbits; bool hasSolution = false;
cout << '请输入总头数和总脚数(空格分隔):';
cin >> heads >> legs;
for (int i = 0; i <= heads; i++)
{
int j = heads - i; // 兔子的数量
if (i * 2 + j * 4 == legs) // 判断是否满足条件
{
hasSolution = true;
chickens = i;
rabbits = j;
break;
}
}
if (hasSolution)
{
cout << '鸡的数量:' << chickens << endl;
cout << '兔的数量:' << rabbits << endl;
}
else
{
cout << '无解' << endl;
}
return 0;
}
程序的运行结果如下:
请输入总头数和总脚数(空格分隔):10 26
鸡的数量:7
兔的数量:3
原文地址: https://www.cveoy.top/t/topic/nGng 著作权归作者所有。请勿转载和采集!