Skip to main content
 首页 » 编程设计

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

2024年10月24日32xiaohuochai

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)) 

我试图在表格中打印年份和主要值(value),但是当我打印出来时,所有结果都是两列 10。

请您参考如下方法:

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

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

  1. 打印年而不是 i,所以它总是相同的值而不是递增
  2. 0在格式声明中 {0:5d}表示以下值中的第 0 个元素,因此您实际上打印了两次年份,第二个应该是 1而不是 0
  3. 您正在使用 d要打印浮点值,d 用于打印整数,您应该使用类似于 {1:.2f} 的内容这意味着“打印这个数字,小数点后两位

一旦您更正了这些问题,您仍然会看到不正确的答案,因为存在更微妙的问题。您正在使用整数值而不是 float 执行除法,这意味着任何小数余数都将被截断,因此 apr / 100将对任何合理的 apr 求值为 0。

您可以通过更正您的输入来解决此问题。 (附带说明一下,对用户输入运行 eval 通常是一个极其危险的想法,因为它会执行输入的任何代码。)使用 float 代替 eval。和 int指定应将输入转换为何种类型的值。

以下是实现上述修复的更正代码。

#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))