Python2.7使用除法和两个输入计算余数

2024-05-29 10:26:14 发布

您现在位置:Python中文网/ 问答频道 /正文

这是我在《编程导论》一书中的一个问题,我不太明白如何在不使用Ifs的情况下做到这一点,因为我们的教授只想要基本的模和除法。我试图得到3个输出。引出序号大于子项(有效),引出序号等于仅输出0和0的子项。气球比孩子少,这不管用。在

# number of balloons
children = int(input("Enter number of balloons: "))

# number of children coming to the party
balloons = int(input("Enter the number of children coming to the party: "))

# number of balloons each child will receive
receive_balloons = int(balloons % children)

# number of balloons leftover for decorations
remaining = children % balloons

print("{:s}""{:d}""{:s}""{:d}".format("Number of balloons  for each child is ", receive_balloons, " and the amount leftover is ", remaining))

print(balloons, "", (remaining))

Tags: ofthetonumberinputpartyintreceive
2条回答

你需要修正变量赋值,你分配给了错误的变量,并实际除数得到receive_balloons正确:

balloons = int(input("Enter number of balloons: "))
children = int(input("Enter the number of children coming to the party: "))

receive_balloons = balloons // children
remaining = balloons % children

# Alternatively
receive_balloons, remaining = divmod(balloons, children)

print("Number of balloons for each child is {} and the amount leftover is {}".format(receive_balloons, remaining))

输出(10/5):

^{pr2}$

输出(10/8):

Enter number of balloons: 10
Enter the number of children coming to the party: 8
Number of balloons for each child is 1 and the amount leftover is 2

注意:在Python2.7中,您应该使用raw_input。在

对于每个子级的引出序号,需要使用//运算符,对于剩余的引出序号,需要使用%运算符

# number of balloons
balloons = int(input("Enter number of balloons: "))

# number of children coming to the party
children = int(input("Enter the number of children coming to the party: "))

receive_balloons, remaining = (balloons // children, balloons % children)

print("{:s}""{:d}""{:s}""{:d}".format("Number of balloons  for each child is ", receive_balloons, " and the amount leftover is ", remaining))

print(balloons, "", (remaining))

相关问题 更多 >

    热门问题