2016-02-13 62 views
-2

我想將輸入的帝國測量轉換爲公制,但轉換不正確,我不知道爲什麼。例如,總重量爲50磅的英制單位輸入導致輸出量爲17.72千克。 歡迎任何建議,評論或代碼更改。 這是我的代碼:已定義公式不正確轉換

# Convert the total weight from Imperial, to Metric units 
def convertWeight(totalWeight): 
    return (totalWeight * 0.45359237) 

# Calculate the cost of transport, by multiplying certain weight conditions by their respective cost per kilograms 
def getRate(totalWeight): 
    if totalWeight <= 2: 
     rate = totalWeight * 1.10 
    elif totalWeight > 2 and totalWeight <= 6: 
     rate = totalWeight * 2.20 
    elif totalWeight > 6 and totalWeight <= 10: 
     rate = totalWeight * 3.70 
    elif totalWeight > 10: 
     rate = totalWeight * 4.20 
    return rate 

# Get the number of boxes 
numBoxes = int(input('Please enter the number of boxes: ')) 
# Get the unit of measurement 
unit = input('Please enter the unit of measurement, Imperial or Metric (as I or M): ') 
# If the inputted unit of measurement does not equal one of these conditions, ask again for the unit of measurement, until one of these characters are inputted. 
while unit not in ['I','M','i','m']: 
    unit = input('Please enter the unit of measurement again, Imperial or Metric (as I or M): ') 

totalWeight = 0 
# For each box, get their respective weight 
for x in range(numBoxes): 
    weight = float(input('Please enter the weight of the boxes: ')) 
# Sum up the total weight by adding the inputted weights 
    totalWeight = totalWeight + weight 
# Does not work, check Parlas answers ; If the inputted unit is Imperial, convert it to Metric 
    if unit in ['I', 'i']: 
     totalWeight = convertWeight(totalWeight) 
    else: 
     totalWeight = totalWeight 

# Calculate the transport cost, by calling the rate function 
transportCost = getRate(totalWeight) 
# Output the number of boxes, the total weight, and the transport cost to the user 
print('The number of boxes is {0}, the total weight is {1:.2f} kilograms, and the transport cost is ${2:,.2f}.' .format(numBoxes, totalWeight, transportCost)) 
+0

你知道你可以使用'number1 和變量 zondo

+0

你能解釋一下,使用代碼嗎? – Nick

+0

@zondo:無論如何,他將自己的'elif's級聯起來,'totalWeight> n'是多餘的。 –

回答

0

的問題是,你的帝國重量換算,

if unit in ['I', 'i']: 
     totalWeight = convertWeight(totalWeight) 

是Get權重循環中,

for x in range(numBoxes): 
    weight = float(input('Please enter the weight of the boxes: ')) 
    # Sum up the total weight by adding the inputted weights 
    totalWeight = totalWeight + weight 

因此,如果(例如)你有2個箱子,每個箱子重25磅,公制重量應該是(25 + 25) * 0.4536,但是你計算的是((25 * 0.4536) + 25) * 0.4536

確保轉換隻發生在之後您獲得了所有權重。

0

我只是減少縮進:

if unit in ['I', 'i']: 
    totalWeight = convertWeight(totalWeight) 
else: 
    totalWeight = totalWeight 

我以前的代碼是每一個人的重量轉換,然後將它添加到總,而不是僅僅將總... 新手的錯誤。