在python 2中舍入没有小数点的浮点值

问题描述 投票:0回答:2

问题是在使用Python 2对百分比值求和之后,将结果值四舍五入而没有任何小数。提供了3个输入

输入1(膳食成本):10.25

输入2(尖端百分比):17

输入3(税率):5

我必须计算小费金额和税额,并将结果与​​膳食成本相加。

我尝试下面的代码:

def solve(meal_cost,tip_percent,tax_percent):

 tip_amt = (meal_cost * tip_percent)/100
 tax_amt =(meal_cost * tax_percent)/100
 total_bill = (meal_cost + tip_amt + tax_amt)
 print int (total_bill)

如果name =='main':

meal_cost = float(raw_input())

tip_percent = int(raw_input())

tax_percent = int(raw_input())

solve(meal_cost, tip_percent, tax_percent)

正确答案是13.但上面的代码给出了12。

请指导我用解决方案获得预期的结果。提前致谢

python-2.7 floating-point
2个回答
0
投票

你应该使用四舍五入。

tip_amt = meal_cost * tip_percent/100
tax_amt =meal_cost * tax_percent/100
total_bill = meal_cost + tip_amt + tax_amt
print round(total_bill)

0
投票

将舍入的和值转换为整数可得到没有小数的预期值。

def solve(meal_cost, tip_percent, tax_percent):
     tip_amt = (meal_cost * tip_percent)/100
     tax_amt =(meal_cost * tax_percent)/100
     total_bill = (meal_cost + tip_amt + tax_amt)
     round_total = round(total_bill)
     return int(round_total)
© www.soinside.com 2019 - 2024. All rights reserved.