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))
这个程序有效,但我想知道如何让公斤只有小数点,所以而不是65磅像545.4544545454克我需要它545克
答案 0 :(得分:0)
有两种方法:
使用 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.
答案 1 :(得分:0)
如果添加行
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.
正是你想要的。