2014-04-14 45 views
0

我的macro_percentages返回3個整數的列表。我已經測試過了,輸出是正確的。但是,當我打印想出我得到的每個打印語句中的0.0s。也有一些是造成我的值變爲0打印整數和浮點數,但得到0的

macro_percentages --> [20,20,60]

代碼:

macro_percentages = ask_macro_percentages() 
print "Your meal plan consists of: " + str(float((macro_percentages[0]/100) * calorie_deficit)) + "g of protein, ", 
print str(float((macro_percentages[1]/100) * calorie_deficit)) + "g of fat, ", 
print "and " + str(float((macro_percentages[2]/100) * calorie_deficit)) + "g of carbohydrates" 
+1

我認爲你是在Python2。 X。您應該嘗試將您的值浮動,或除以100.0 – sberry

+1

我建議在開始計算之前簡單地添加此行:'macro_percentages = [float(value)for macro_percentages]' –

回答

6
str(float((macro_percentages[0]/100) 

首先,macro_percentages[0]100分。因爲macro_percentages[0]int,並且100int,Python 2使用整數除法,給出0。只有在那之後,0才轉換爲float,然後是str。但是這個分數值已經失去了。

您可以把這個在你的腳本的頂部,使用浮點除法(Python 3中默認):

from __future__ import division 

或包裹浮子分子:

str((float(macro_percentages[0])/100) 

或分割通過浮法100.0

str(macro_percentages[0]/100.0) 
+0

好吧,我明白了。我會給這個鏡頭謝謝! – Liondancer

+0

作品謝謝!欣賞它! – Liondancer

1

使用整數噸在Python除以當返回的將是一個整數他值那麼所有你需要做的是改變100至100.0左右(我取代10 calorie_deficit因爲我需要對其進行測試)希望這有助於

macro_percentages = [20,20,60] 

print "Your meal plan consists of: " + str(float((macro_percentages[0]/100.0) * 10)) + "g of protein, ", 
print str(float((macro_percentages[1]/100.0) * 10)) + "g of fat, ", 
print "and " + str(float((macro_percentages[2]/100.0) * 10)) + "g of carbohydrates"