Python鸡兔同笼的输出格式问题
来自python初学者的求助,这是一个鸡兔同笼的问题,我的算法和答案应该都没有问题,问题出在输出格式上,题目见下图以下是我写的代码
counts = int(input())
res = []
while counts > 0:
head = int(input())
feet = int(input())
feet1 = head * 4
feet2 = feet1 - feet
head1 = int(feet2 / 2)
head2 = int(head - head1)
if head1 % 1 == 0 and head2 % 1 == 0 and head1 >= 0 and head2 >= 0:
temp1 = str(head1)
temp2 = str(head2)
res.append(temp1)
res.append(temp2)
else:
x = "No answer"
res.append(x)
counts -= 1
for i in res:
print(i, end=" ")
学校oj网站的要求是必须在输入结束后一次性将所有计算结果一次性输出出来,但是我写的代码需要需要一次一次的把每组结果print出来,请问各位大佬,应该如何修改代码,才能实现正确的输出格式?马上就要参加新生赛了,萌新跪谢!!! 看不见lz的图,但是把lz的代码运行了一下,不怎么好理解,改了一下:counts = int(input('項目組數'))
res = []
x = 1
while x <= counts:
print('第',x,'組項目')
head = int(input('頭'))
feet = int(input('腳'))
feet1 = head * 4
feet2 = feet1 - feet
head1 = int(feet2 / 2)
head2 = int(head - head1)
if head1 % 1 == 0 and head2 % 1 == 0 and head1 >= 0 and head2 >= 0:
temp = '第' + str(x) + '組,雞:' + str(head1) + ',兔:' + str(head2)
res.append(temp)
else:
x = "No answer"
res.append(x)
x += 1
for i in res:
print(i)
运行结果:
項目組數3
第 1 組項目
頭3
腳8
第 2 組項目
頭3
腳10
第 3 組項目
頭3
腳12
第1組,雞:2,兔:1
第2組,雞:1,兔:2
第3組,雞:0,兔:3
我写的代码修改过,所以可能比较乱,希望大家能帮我看看{:10_266:} counts = []
while True:
count = input()
if count == '':
break
else:
counts.append(count)
====
既然是需要提示,那到这里应该足够了 {:10_277:} 本帖最后由 LZRoc 于 2021-10-14 11:21 编辑
抛砖引玉{:10_266:}
"""鸡兔同笼"""
res = []
number = 1
while True:
try:
counts = int(input("请输入项目组数:"))
if counts > 10 or counts <= 0:
raise ValueError
break
except ValueError:
print("项目组数控制在10组以内")
continue
print("输入头数和脚数时,请以空格隔开!")
while number <= counts:
print("第",number,"组项目:")
while True:
try:
head,feet = map(int,input("请输入头数和脚数:").split())
if head < 0 or feet <0:
raise ValueError
break
except ValueError:
print("请输入两个正整数")
continue
headC = (head * 4 - feet)/ 2#计算鸡的数量
headR = head - headC#计算兔的数量
if headR % 1 == 0 and headC % 1 == 0 and headR >= 0 and headC >= 0:
temp ="第" + str(number) +"组项目,鸡:"+ str(int(headC)) + "只,兔:"+ str(int(headR)) + "只"
res.append(temp)
else:
x = "第" + str(number) + "组项目,No answer"
res.append(x)
number += 1
for i in res:
print(i)
页:
[1]