gpt4 book ai didi

Python - 如何在不四舍五入的情况下删除小数

转载 作者:太空宇宙 更新时间:2023-11-04 08:49:43 24 4
gpt4 key购买 nike

我对 python 有点陌生,我想测试一下,我的想法是制作一个脚本,它可以查看您可以用一定数量的钱购买多少东西。不过这个项目的问题是,我不知道去掉小数点,就像你喜欢如果你有 1.99 美元,一杯苏打水要花 2 美元,从技术上讲,你没有足够的钱买它。这是我的脚本:

Banana = 1
Apple = 2
Cookie = 5

money = input("How much money have you got? ")
if int(money) >= 1:
print("For ", money," dollars you can get ",int(money)/int(Banana),"bananas")
if int(money) >= 2:
print("Or ", int(money)/int(Apple), "apples")
if int(money) >= 5:
print("Or ", int(money)/int(Cookie)," cookies")
else:
print("You don't have enough money for any other imported elements in the script")

现在,如果我在这个脚本中输入例如 9,它会说我可以得到 1.8 个 cookies ,我如何让它在输入 fx 9 时说我可以得到 1 个 cookies ?

最佳答案

我怀疑您使用的是 Python 3,因为您说的是在将两个整数 9 和 5 相除时得到 float 结果 1.8。

所以在 Python 3 中,有一个整数除法运算符 // 你可以使用:

>>> 9 // 5
1

对比

>>> 9 / 5
1.8

对于 Python 2,/ 运算符默认执行整数除法(当两个操作数都是整数时),除非您使用 from __future__ import division 使其行为像 Python 3。

关于Python - 如何在不四舍五入的情况下删除小数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36643629/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com