我想將輸入的帝國測量轉換爲公制,但轉換不正確,我不知道爲什麼。例如,總重量爲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))
你知道你可以使用'number1和變量
zondo
你能解釋一下,使用代碼嗎? – Nick
@zondo:無論如何,他將自己的'elif's級聯起來,'totalWeight> n'是多餘的。 –