我正在为我的班级输入一个程序,这个问题措辞很奇怪,但是我已经把问题放入我的代码中了,我是否正确地将这些数字称为浮点数? 简单的问题,但我对其他做事方式持开放态度。
print " This program will calculate the unit price (price per oz) of store items,"
print " you will input the weight in lbs and oz, the name and cost."
item_name = (input("Please enter the name of the item. "))
item_lb_price = float(input("Please enter the price per pound of your item "))
item_lbs = float(input("please enter the pounds of your item. "))
item_oz = float(input("plese enter the ounces of your item. "))
unit_price = item_lb_price / 16
total_price = item_lb_price * (item_lbs + item_oz / 16)
print "the total price per oz is", unit_price
print "the total price for", item_name, "is a total of", total_price
答案 0 :(得分:1)
如果是python 2,你应该使用raw_input而不是input。 如果它是python 3,你应该在括号中包含你想要打印的值。
是的,您正在正确使用float函数,但未验证输入是否正确。它有责任,甚至可能抛出错误。
除了python 2的程序不正确之外因为输入()而对python 3不正确,因为使用了print语句。
你应该用漂浮物来代替:16.0而不是16。
答案 1 :(得分:1)
你的漂浮物很好。
您需要使用raw_input
来获取字符串。
input("Enter a number")
相当于eval(raw_input("Enter a number"))
。目前,代码尝试将输入计算为代码(作为python表达式运行)。
15:10:21 ~$ python so18967752.py
This program will calculate the unit price (price per oz) of store items,
you will input the weight in lbs and oz, the name and cost.
Please enter the name of the item. Apple
Traceback (most recent call last):
File "so18967752.py", line 6, in <module>
item_name = (input("Please enter the name of the item. "))
File "<string>", line 1, in <module>
NameError: name 'Apple' is not defined
其他评论:
稍微清理过的表格:
banner = '''
This program will calculate the unit price (price per oz) of store items.
You will input the weight in lbs and oz, the name and cost.
'''
print banner
item_name = raw_input("Please enter the name of the item. ")
item_lb_price = float(raw_input("Please enter the price per pound of your item."))
item_lbs = float(raw_input("Please enter the pounds of your item."))
item_oz = float(raw_input("plese enter the ounces of your item."))
unit_price = item_lb_price / 16.0
total_price = item_lb_price * (item_lbs + (item_oz / 16.0))
print "The total price per oz is", unit_price
print "The total price for", item_name, "is a total of", total_price
答案 2 :(得分:0)
python中的分区是默认使用整数,所以如果你想要一个浮点结果你应该除以16.0
unit_price = item_lb_price / 16.0