[英]pounds to metric python program
def poundsToMetric(pounds):
kilograms = pounds / 2.2
grams = kilograms * 1000
return int(kilograms), grams % 1000
pounds = float(input("How many Pounds? "))
kg, g = poundsToMetric(pounds)
print('The amount of pounds you entered is {}. '\
'This is {} kilograms and {} grams.'.format(pounds, kg, g))
這個程序有效,但我想知道如何讓公斤只帶小數點,而不是像 545.4544545454 克這樣的 65 磅,我需要它是 545 克
有兩種方式:
使用round()內置函數
def poundsToMetric(pounds): kilograms = pounds / 2.2 grams = kilograms * 1000 return int(kilograms), grams % 1000 pounds = float(input("How many Pounds? ")) kg, g = poundsToMetric(pounds) print('The amount of pounds you entered is {}. This is {} kilograms and {} grams.'.format(pounds, kg, round(g)))
使用int()轉換來獲取值的整數部分:
def poundsToMetric(pounds): kilograms = pounds / 2.2 grams = kilograms * 1000 return int(kilograms), grams % 1000 pounds = float(input("How many Pounds? ")) kg, g = poundsToMetric(pounds) print('The amount of pounds you entered is {}. This is {} kilograms and {} grams.'.format(pounds, kg, int(g)))
分別查看以下每種方式的輸出:
➜ python help.py
How many Pounds? 65
The amount of pounds you entered is 65.0. This is 29 kilograms and 545.0 grams.
➜ python help.py
How many Pounds? 65
The amount of pounds you entered is 65.0. This is 29 kilograms and 545 grams.
如果添加行
print type(grams%1000)
你會得到輸出
<type 'float'>
所以這顯然是返回一個浮點數。 將其轉換為int
以獲得所需的結果。
而不是這樣做:
return int(kilograms), grams % 1000
做這個:
return int(kilograms), int(grams % 1000)
現在你的程序的輸出是:
The amount of pounds you entered is 65. This is 29 kilograms and 545 grams.
正是你想要的。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.