2

クラスのプログラムを入力しています。問題は非常に奇妙に表現されていますが、問題のコードを入力しました。数値を float として正しく宣言していますか? 簡単な質問ですが、私は物事を行う他の方法に心を開いています。

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
4

3 に答える 3

1

あなたのフロートは大丈夫です。

raw_input文字列を取得するには、whileを使用する必要があります。

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

他のコメント:

  1. 上部の複数行のバナーの場合、文字列を複数行の文字列として宣言し、それを出力します。
  2. 範囲が入力に対して意味があることを確認します (検証)。もちろん、これがクラスの場合は、この時点に達していない可能性があります (if/else を見ましたか?)
  3. 定数を明示的に浮動小数点数にして、デフォルトで整数除算にならないようにする

少しクリーンアップされたフォーム:

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
于 2013-09-23T20:08:40.953 に答える
1

Python 2 の場合は、input の代わりに raw_input を使用する必要があります。Python 3 の場合は、印刷する値を括弧で囲む必要があります。

はい、 float 関数を正しく使用していますが、入力が正しいことを確認していません。責任があり、エラーをスローする可能性さえあります。

さらに、プログラムは、input() のために python 2 では正しくなく、print ステートメントを使用しているため、python 3 では正しくありません。

そして、float で割る必要があります: 16 ではなく 16.0 です。

于 2013-09-23T20:06:10.747 に答える
0

Python の除算はデフォルトで整数を使用するため、浮動小数点の結果が必要な場合は 16.0 で除算する必要があります。

unit_price = item_lb_price / 16.0
于 2013-09-23T20:04:00.390 に答える