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

一个人

我想要它,以便告诉您参加聚会需要多少个热狗和面包包。一个包中有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!')

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

亚当·史密斯

您应该考虑采用其他方式。而不是在除法之后检查您是否有整数:使用模运算符检查除法是否会得到整数%

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

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

在特定情况下,数组中数字的总和

如何在特定情况下捕获OnTouchEvent?

如何在特定情况下使用JavaScript加载特定的CSS文件?

如何在特定情况下的Django注册自定义字段中使required = false

在我的特定情况下,如何在C#中选择正确的循环语句?

Jenkins脚本化管道:如何在此特定情况下应用@NonCPS注释

如何在整个游戏的特定情况下使用玩家的输入

如何在特定情况下将while循环转换为递归方法

如何在我的特定情况下形成嵌套数组的数组?

在特定情况下如何抑制声纳法则?

在特定情况下如何使用高阶结构

在特定情况下如何合并数据框?

在特定情况下,如何使JRadioButton透明?

在sql server中的特定情况下除以零

在 python 中, input() 函数在这种特定情况下对我不起作用

特定情况下的时序图

特定情况下的开关盒

在特定情况下替换字符

特定情况下的分段错误

如何在不更改任何格式的情况下删除文件中的特定列

如何在没有任何循环的情况下获取php中的特定键数组

如何在特定情况下在 Sequelize 中获取关联元素

如何在不删除Python中任何内容的情况下写入CSV文件?

如何在不覆盖python中任何数据的情况下合并两个文件?

如何在Python中没有任何模块的情况下求解方程?

如何在 Python 中没有任何循环(如:for、while 等)的情况下递归 JSON 文件

如何在不舍入的情况下截断BigDecimal

如何在c中不舍入的情况下提取双精度值的小数部分

如何使用Meteor.users.update在特定情况下的对象中包含一个变量?