Python - 如何在不四舍五入的情况下删除小数
Python - How to remove decimals without rounding up
我对 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 个饼干,我如何让它在输入 fx 9 时说我可以得到 1 个饼干?
我怀疑您使用的是 Python 3,因为当您将两个整数 9 和 5 相除时,您说的是得到浮点数结果 1.8。
所以在Python3中,有一个整数除法运算符 //
你可以使用:
>>> 9 // 5
1
对
>>> 9 / 5
1.8
至于 Python 2,默认情况下 /
运算符执行整数除法(当两个操作数都是整数时),除非您使用 from __future__ import division
使其表现得像 Python 3.
使用math.floor
更新代码:
import math
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 ",math.floor(int(money)/int(Banana)),"bananas")
if int(money) >= 2:
print("Or ", math.floor(int(money)/int(Apple)), "apples")
if int(money) >= 5:
print("Or ", math.floor(int(money)/int(Cookie))," cookies")
else:
print("You don't have enough money for any other imported elements in the script")
我对 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 个饼干,我如何让它在输入 fx 9 时说我可以得到 1 个饼干?
我怀疑您使用的是 Python 3,因为当您将两个整数 9 和 5 相除时,您说的是得到浮点数结果 1.8。
所以在Python3中,有一个整数除法运算符 //
你可以使用:
>>> 9 // 5
1
对
>>> 9 / 5
1.8
至于 Python 2,默认情况下 /
运算符执行整数除法(当两个操作数都是整数时),除非您使用 from __future__ import division
使其表现得像 Python 3.
使用math.floor
更新代码:
import math
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 ",math.floor(int(money)/int(Banana)),"bananas")
if int(money) >= 2:
print("Or ", math.floor(int(money)/int(Apple)), "apples")
if int(money) >= 5:
print("Or ", math.floor(int(money)/int(Cookie))," cookies")
else:
print("You don't have enough money for any other imported elements in the script")