Python 代码在某些版本中不起作用

Python Code not Working in Certain Versions

所以为了我的学校,我必须制作这个脚本来计算一顿饭的小费和税金。我在 class 中领先于所有人,所以没有其他人遇到过这个问题。

该代码在我的电脑上 Python3 IDLE 中运行良好,在 repl.it. Oddly enough, at my school's IDLE, which is private, and Python Fiddle, which is pretty much the same 小费和税金未正确计算时也运行良好。

此外,还有其他一些错误,例如显示多余的数字或数字不足。我尽我最大的努力用字符串切片来解决这个问题,但它没有用。我知道的唯一其他方法是使用 if 不允许的语句。

任何帮助将不胜感激,在此先感谢。

代码:

#Name
#9/20/16
#This program calculates the total cost of a meal.

def main():
    #INPUT
    meal = float(30.96)
    am = int(input("How many meals would you like? "))
    tx = int(input("What is the tax %? "))
    tp = int(input("How much % do you want to tip?" ))
#CALCULATIONS   
    subT = am*meal
    tax1 = tx/100
    tax = tax1*subT
    subTotalWithTax = subT + tax
    tip1 = tp/100
    tip = tip1*subTotalWithTax
    total = subTotalWithTax + tip
    clTip = str(tip)[0: 4]
    clTax = str(tax)[0: 4]
    clTotal = str(total)[0: 6]
    clSubT = str(subT)[0: 6]
#OUTPUT
    print("-----------------------------------------------")
    print("Items: ")
    print(str(am) + " Overloaded Potato Skins ------------- .99")
    print(str(am) + " Grilled Top Sirloin 12oz ------------ .49")
    print(str(am) + " Sweet Tea --------------------------- .99")
    print(str(am) + " Southern Pecan Pie ------------------ .99")
    print("------------------------------------------------")
    print("Totals: ")
    print("Subtotal: ----------------------------- $" + str(clSubT))
    print("Tax: ---------------------------------- $" + str(clTax))
    print("Tip: ---------------------------------- $" + str(clTip))
    print("Total --------------------------------- $" + str(clTotal))
    print("------------------------------------------------")
main()

我同意 edwinksl 的评论,请检查您学校计算机上的 python 是哪个版本。您可以右键单击 python 文件并单击空闲编辑,版本应位于页面的右上角(文件路径旁边)。

不过我还有另外一张纸条。您的老师可以另外指定,但通常小计是餐费加税的总和。然后您的小费将根据此计算并添加。(除非您的老师另有说明,否则请遵循他们的指导方针。)

subT = am*meal
tax1 = tx/100
tax = tax1*subT
subTotalWithTax = subT + tax
tip1 = tp/100
tip = tip1*subTotalWithTax
total = subTotalWithTax + tip

您得到 $0 作为答案的事实可能表明 python(2,可能)仍然将数字表示为整数。尝试显式转换为浮点数。 如:

tip1 = tp/100.0  # instead of 100

tx = float(input("What is the tax %? "))

还有显示的裁剪有点乱,试试

print("Total --------------------------------- ${}".format(total))

.format() 就是您要找的技巧。有一些方法可以只显示两位小数,检查一下 SO 或 https://pyformat.info/——但一定要试试 "{:.2f}".format(total):-)


编辑 或者,没有 formatprint("%.2f" % total)

现在,对于一种完全复杂的价格打印方式(即,如果不允许格式化但允许字符串操作):

totalDollar, totalCent = str(total).split('.')
totalCent += "00"
print("Total --------------------------------- $" + totalDollar + "." + totalCent[:2])