Skip to main content
 首页 » 编程设计

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

2025年05月04日27hnrainll

我对 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。