Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/302.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python-如何删除小数而不进行取整_Python_Import_Decimal_Rounding_Currency - Fatal编程技术网

Python-如何删除小数而不进行取整

Python-如何删除小数而不进行取整,python,import,decimal,rounding,currency,Python,Import,Decimal,Rounding,Currency,我对python有点陌生,我想测试一下,我的想法是制作一个脚本,看看你能用一定的钱买多少东西。 不过,这个项目的问题是,我不知道去掉小数,就像你喜欢的那样,如果你有1,99美元,一杯汽水的价格是2美元,从技术上讲,你没有足够的钱来买它。这是我的剧本: Banana = 1 Apple = 2 Cookie = 5 money = input("How much money have you got? ") if int(money) >= 1: print("For ", mon

我对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相除时,您正在谈论得到浮点结果1.8

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

>>> 9 // 5
1
vs


对于Python2,默认情况下,
/
运算符进行整数除法(当两个操作数都是整数时),除非您使用
from\uuuuu future\uuuu导入除法
使其行为与Python3类似。

使用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")

非常感谢,没想到会这么简单:值得注意的是,
/
操作符也存在于Python2(非古代版本)中,无论使用哪一版本的Python,它都是拼写整数除法的首选方法。即使在Python2中,当需要整数除法时也不要使用
/
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")