2016-02-13 33 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 

我以前的代码是每一个人的重量转换,然后将它添加到总,而不是仅仅将总... 新手的错误。