2015-10-26 52 views
-1
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克65磅是像545.4544545454克磅公制Python程序

+0

可能重复的[浮点数学是否被破坏?](http://stackoverflow.com/questions/588004/is-floating-point-math-broken) – Hypaethral

+0

可能的重复[你如何在一个数字中取整Python的?](http://stackoverflow.com/questions/2356501/how-do-you-round-up-a-number-in-python) –

回答

0

有两种方式:

  1. 使用轮()内置功能

    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))) 
    
  2. 使用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. 
0

如果您添加该行

print type(grams%1000) 

您将获得输出

<type 'float'> 

所以这显然返回一个浮点数。将其转换为int以获得理想的结果。

而不是做这个的:

​​

这样做:

return int(kilograms), int(grams % 1000) 

现在输出你的程序是:

The amount of pounds you entered is 65. This is 29 kilograms and 545 grams. 

你想要的究竟是什么。