python中表的计算问题.(简单的销售税计划)



我在python中处理的程序遇到了问题,大多数程序都能工作,但当我试图在程序结束时计算总数时,它实际上并没有添加总数,更像是添加了两个字符串并将它们放在一起。

以下是我迄今为止的代码。

#welcome message
print("hello customer!n")
print("How much did you spend on your most recent purchase?")
pre_tax = float(input())
STATE_t =0.05
COUNTY_t =0.025
print("nnOkay, if you spent $" +str(pre_tax)+ " then you spent a total of:")

print('{0:<14}{1:>1}{2:>1}'.format('Pre Tax:','$', pre_tax))
state_t = (pre_tax * STATE_t)
state_t = "{:.2f}".format(state_t)
print('{0:<14}{1:>1}{2:>5}'.format('State Tax:','$', state_t))
county_t = (pre_tax * COUNTY_t)
county_t = float(county_t)
county_t= "{:.2f}".format(county_t)
print('{0:<14}{1:>1}{2:>5}'.format('County Tax:','$', county_t))
total = (county_t+state_t )
#total = float(total)
#total = "{:.2f}".format(total)
print('{0:<14}{1:>1}{2:>1}'.format('Total:','$', total))

这是我得到的输出。

hello customer!
How much did you spend on your most recent purchase?
100
Okay, if you spent $100.0 then you spent a total of:
Pre Tax:      $100.0
State Tax:    $ 5.00
County Tax:   $ 2.50
Total:        $2.505.00
> 

您的问题是将数值state_tcounty_t转换为字符串值,以便打印它们。因此,total = (county_t+state_t)行将两个字符串相加,而不是两个数字。以下是您的代码,其中包含了做正确事情的修复程序(不包括代码的早期部分(:

state_t = (pre_tax * STATE_t)
state_t_str = "{:.2f}".format(state_t)
print('{0:<14}{1:>1}{2:>5}'.format('State Tax:','$', state_t_str))
county_t = (pre_tax * COUNTY_t)
county_t = float(county_t)
county_t_str = "{:.2f}".format(county_t)
print('{0:<14}{1:>1}{2:>5}'.format('County Tax:','$', county_t_str))
total = (pre_tax+county_t+state_t)
total_str = "{:.2f}".format(total)
#total = float(total)
#total = "{:.2f}".format(total)
print('{0:<14}{1:>1}{2:>1}'.format('Total:','$', total_str))

正如你所看到的,我为格式化的字符串形式的数字创建了单独的值,这样我以后仍然可以使用数字形式进行计算。我还将原始金额添加到总数中,这似乎很合适。

以下是您的示例在进行代码更改后的输出:

Okay, if you spent $100.0 then you spent a total of:
Pre Tax:      $100.0
State Tax:    $ 5.00
County Tax:   $ 2.50
Total:        $107.50

最新更新