用FOR循环计算利息、本金和年数的总和

2024-04-27 12:12:50 发布

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

我试图创建一个程序,询问用户他们的本金,利率,和总年限。我希望我的计划能向他们展示他们每年的总回报率。我想从第一年开始。当我运行脚本时,它只显示一年的总利息。这是我到目前为止的情况。在

#Declare the necessary variables.
princ = 0
interest = 0.0
totYears = 0
year = 1

#Get the amont of principal invested.
print("Enter the principal amount.")
princ = int(input())

#Get the interest rate being applied.
print("Enter the interest rate.")
interest = float(input())

#Get the total amount of years principal is invested.
print ("Enter the total number of years you're investing this amonut.")
totYears = int(input())

for years in range(1, totYears):
    total=year*interest*princ
    years += 1

print (total)

谢谢你的帮助。在


Tags: oftheprincipalinputgetamountyeartotal
1条回答
网友
1楼 · 发布于 2024-04-27 12:12:50

这里有一些问题:

for years in range(1, totYears):
    total=year*interest*princ
    years += 1

print (total)
  1. 你在循环中改变了。别这样,for语句会为您处理这些问题。你的干扰使在循环中每次改变2。在
  2. 每次循环过程中,您都会放弃上一年的利息,并计算新的利息。print语句在循环之外,因此只打印total的最终值。在
  3. 你的循环指数是,但是你已经计算了变量,它总是1。我多年前学到的一种编程技巧是永远不要使用复数变量名。在

也许你需要这个:

^{pr2}$

相关问题 更多 >