作者制作不易,关注、点赞、收藏一下吧!
目录
1.Python实现
首先,我们需要输入头和脚的数量:
head = int(input("请输入头的数量: "))
feet = int(input("请输入脚的数量: "))
input() 实现输入,int() 实现把字符串型( str )换为整型( int )。
然后,进行循环枚举:
for i in range(0, head):
for j in range(0, feet):
if i + j == head and 2 * i + 4 * j == feet:
print("有", i, "只兔,有", j, "只鸡。")
运行结果:
验算后没问题,说明无逻辑错误。
或者,循环还有另一种方法:
for i in range(0, head):
j = head - i
if 2 * i + 4 * j == feet:
print("有", i, "只兔,有", j, "只鸡。")
运行结果:
也没有问题,而且这样运行得更快。
2.C++实现
和Python版本一样,也要先输入头和脚的数量:
#include <iostream>
using namespace std;
int main()
{
int head, feet;
cin >> head >> feet;
}
然后就是循环枚举:
#include <iostream>
using namespace std;
int main()
{
int head, feet;
cin >> head >> feet;
for (int i = 0; i <= head; i++)
{
for (int j = 0; j <= feet; j++)
{
if (i + j == head && 2 * i + 4 * j == feet)
{
cout << "有" << i << "只兔,有" << j << "只鸡。";
}
}
}
}
和Python一样,C++也有第两个方法:
#include <iostream>
using namespace std;
int main()
{
int head, feet;
cin >> head >> feet;
for (int i = 0; i <= head; i++)
{
j = head - i;
if (2 * i + 4 * j == feet)
{
cout << "有" << i << "只兔,有" << j << "只鸡。";
}
}
}
标签:head,鸡兔同笼,Python,C++,feet,int,using
From: https://blog.csdn.net/a_pjx_z/article/details/141966951