在特定情况下如何在python中舍入任何数字

时间:2019-02-18 02:23:24

标签: python python-3.x

我想要它,以便告诉您参加聚会需要多少个热狗和面包的包装。一个包中有10个热狗,一个包中有8个热狗。这怎么了?

HotDogInAPack = 10
BunInAPack = 8

Guests = int(input("How many guests are attending?"))
HotDogsEachGuestWants = int(input("How many hotdogs does each guest 
want?"))
AmountNeeded = Guests * HotDogsEachGuestWants
HotDogPackagesNeededINCOMPLETE = AmountNeeded / HotDogInAPack
BunPackagesNeededINCOMPLETE = AmountNeeded / BunInAPack
if type(HotDogPackagesNeededINCOMPLETE) == float:
    ThereAreHotDogLeftOvers = 1
    HotDogPackagesNeededFLOAT = HotDogPackagesNeededINCOMPLETE + 1
    HotDogPackagesNeeded = (format (HotDogPackagesNeededFLOAT, '.0f'))
    LeftOversHotDog = AmountNeeded % HotDogInAPack
else:
    ThereAreHotDogLeftOvers = 2
if type(BunPackagesNeededINCOMPLETE) == float:
    ThereAreBunLeftOvers = 1
    BunPackagesNeededFLOAT = BunPackagesNeededINCOMPLETE + 1
    BunPackagesNeeded = (format (BunPackagesNeededFLOAT, '.0f'))
    LeftOversBun = AmountNeeded % BunInAPack
else:
    ThereAreBunLeftOvers = 2
if ThereAreHotDogLeftOvers == 1:
    print('You need', HotDogPackagesNeeded, 'hotdog packages and you will 
    have', LeftOversHotDog, 'left over hotdogs.')
else:
    print('You need', HotDogPackagesNeeded, 'hotdog packages and you will 
    have no left over hotdog buns!')
if ThereAreBunLeftOvers == 1:
    print('You need', BunPackagesNeeded, 'hotdog bun packages and you 
    will have', LeftOversBun, 'left over hotdog buns.')
else:
    print('You need', BunPackagesNeeded, 'hotdog bun packages and you 
    will have no left over hotdog buns!')

数学全错了!我不知道我做错了什么。

1 个答案:

答案 0 :(得分:2)

您应该考虑以其他方式执行此操作。而不是检查除后的 是否有整数:使用模运算符%

检查除数是否会导致整数
if amount_needed % hot_dogs_in_pack == 0:
    hot_dog_packages_needed = amount_needed // hot_dogs_in_pack
else:
    hot_dog_packages_needed = amount_needed // hot_dogs_in_pack + 1  # one more than the floor div

实际上,使用divmod可以很容易地做到这一点。

packages, leftovers = divmod(amount_needed, hot_dogs_in_pack)
if leftovers:
    packages += 1
    leftovers = (packages * hot_dogs_in_pack) % amount_needed
相关问题