首页 > 解决方案 > 如何制作一个简单的利息计算器

问题描述

我正在尝试挑战练习。我正在尝试使用输入来决定您将支付多少贷款。非常基本的东西 - 但是当我打印时,我会一遍又一遍地重复输入中回答的任何内容,我无法弄清楚我哪里出错了。我试图运行的代码是:

# $200 a month at 1.7% interest a year. Automate total based on months using user input.

months_given = input("How many months? ")

monthly_base = 200
yearly_tax = (1.7 / 100 / 12)
monthly_tax = (200 * yearly_tax)
monthly_total = int(monthly_tax + 200)
total = int(months_given * monthly_total)


print(f"You will need to pay: ${round(total, 2)}")

我尝试过使用 for/while 循环,但我还不精通这些循环,我仍在尝试了解它们的工作原理。

标签: python

解决方案


你需要先解析你的input然后使用它。当你使用input它时返回str

在这一total = int(months_given * monthly_total)行。months_givenisstr并且当您使用*运算符并且第二个操作数是int,str重复值。

正确的:

months_given = input("How many months? ")
months_given = int(months_given) # <-- here
monthly_base = 200
yearly_tax = (1.7 / 100 / 12)
monthly_tax = (200 * yearly_tax)
monthly_total = int(monthly_tax + 200)
total = int(months_given * monthly_total)


print(f"You will need to pay: ${round(total, 2)}")

推荐阅读