确定循环中的python字符串格式错误

2024-03-29 05:56:07 发布

您现在位置:Python中文网/ 问答频道 /正文

def main():
    #Get amount of principal, apr, and # of years from user
    princ = eval(input("Please enter the amount of principal in dollars "))
    apr = eval(input("Please enter the annual interest rate percentage "))
    years = eval(input("Please enter the number of years to maturity "))

    #Convert apr to a decimal
    decapr = apr / 100

    #Use definite loop to calculate future value
    for i in range(years):
        princ = princ * (1 + decapr)
        print('{0:5d} {0:5d}'.format(years, princ))

我试图在一个表中打印年份和主值,但打印出来的结果是两列10。你知道吗


Tags: ofthetoinprincipalinputdefeval
1条回答
网友
1楼 · 发布于 2024-03-29 05:56:07

所以你有几个问题。第一个问题是显示问题。你知道吗

输出语句print('{0:5d} {0:5d}'.format(years, princ))有几个问题。你知道吗

  1. 打印年份而不是i,所以它总是相同的值而不是递增
  2. format语句{0:5d}中的0表示下列值中的第0个元素,因此实际上要打印两次年份,第二个应该是1,而不是0
  3. 你用d来打印应该是浮点值的东西,d是用来打印整数的,你应该用{1:.2f}这意味着“用2位小数打印这个数字”

一旦你纠正了这些,你仍然会看到错误的答案,因为一个更微妙的问题。您正在使用整数值而不是浮点数执行除法,这意味着任何十进制余数都将被截断,因此apr / 100对于任何合理的apr都将计算为0

您可以通过更正输入来解决此问题。(顺便说一句,对用户输入运行eval通常是一个非常危险的想法,因为它将执行输入的任何代码。)而不是eval,使用floatint来指定输入应转换为哪些类型的值。你知道吗

下面是实现上述修复的更正代码。你知道吗

#Get amount of principal, apr, and # of years from user
princ = float(input("Please enter the amount of principal in dollars "))
apr = float(input("Please enter the annual interest rate percentage "))
years = int(input("Please enter the number of years to maturity "))

#Convert apr to a decimal
decapr = apr / 100

#Use definite loop to calculate future value
for i in range(years):
    princ = princ * (1 + decapr)
    print('{0} {1:.2f}'.format(i, princ))

相关问题 更多 >