打印整数和浮点数但得到0

时间:2014-04-14 22:37:04

标签: python

我的macro_percentages会返回3个整数的列表。我已经测试了这个,输出是正确的。但是,当我打印时,在每个打印语句中都认为我得到的是0.0s。有些东西导致我的值变为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"

2 个答案:

答案 0 :(得分: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

或者将float包装到分子:

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

或除以浮点100.0

str(macro_percentages[0]/100.0)

答案 1 :(得分: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"
相关问题