2016-04-15 19 views
1

我有点新入Python,我想测试它,我的想法是制作一个脚本,它会查看您可以购买一定数量的资金。 虽然这个项目的问题是,我不知道删除小数,就像你喜欢,如果你有1,99美元和苏打耗资2美元,你在技术上没有足够的钱。这里是我的脚本:Python - 如何删除小数而不会舍入

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饼干,我如何让它说我可以得到1块饼干进入外汇9时?

回答

5

我怀疑你是使用Python 3,因为你是在谈论得到float结果1.8,当您将两个整数9和在Python 3 5

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

>>> 9 // 5 
1 

VS

>>> 9/5 
1.8 

对于Python 2里,/操作默认完成整数除法(当两个操作数均为整数),除非你使用from __future__ import division,使其行为像Python 3

+0

非常感谢,没想到它变得那么容易:D –

+0

值得注意的是''//运算符也存在于Python 2的(非古代版本)中,并且它是拼写整数的首选方法不管您使用的是哪个版本的Python。即使在Python 2中,也不要在整数除法中使用'/'。 –

0

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