如何让Python复利计算器给出正确的答案

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

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

早前曾发布过一个关于错误的问题。多亏了这里的几个人,我才解决了这个问题。现在我遇到了我的复利计算器的问题,当你输入本金、复利(年、月等)、利率(0.03等)和年数时,计算错误。 其他Q链接:final = P * (((1 + (r/n)) ** (n*t))) TypeError: unsupported operand type(s) for /: 'str' and 'int' 所以在前面的代码中,我去掉了p=10000,n=12,r=0.08,因为当你输入不同的数字时,它会给出一个很大的数字。我希望它能用输入的数字来计算,但事实并非如此

# User must input principal, Compound rate, annual rate, and years.
P = int(input("Enter starting principle please. "))
n = int(input("Enter Compound intrest rate.(daily, monthly, quarterly, half-year, yearly) "))
r = float(input("Enter annual interest amount. (decimal) "))
t = int(input("Enter the amount of years. "))

final = P * (((1 + (r/n)) ** (n*t)))
#displays the final amount after number of years.
print ("The final amount after", t, "years is", final)
# At the moment it is displaying a very random number.

Enter starting principle please. 1000
Enter Compound intrest rate.(daily, monthly, quarterly, half-year, yearly) 1
Enter annual interest amount. (decimal) 0.01
Enter the amount of years. 1
The final amount after 1 years is 1010.0

最终金额应为1000.10。不知道发生了什么。试着看看是否有办法使P,n,r等于用户输入的数字,从而得到正确的最终答案。

提前谢谢。


Tags: andoftheinputrateis数字amount
3条回答

基于此: 复利公式 FV=P(1+r/n)^Yn, 其中P是起始本金,r是年利率,Y是投资年数,n是每年复利期数。FV是未来价值,意味着本金在Y年后增长到的金额。

P = int(input("Enter starting principle please. "))
n = int(input("Enter number of compounding periods per year. "))
r = float(input("Enter annual interest rate. e.g. 15 for 15% "))
y = int(input("Enter the amount of years. "))

FV = P * (((1 + ((r/100.0)/n)) ** (n*y)))

print ("The final amount after", y, "years is", FV)

如果你对百分比感兴趣,你应该在代码中处理。

final = P * (((1 + (r/(100.0 * n))) ** (n*t)))

请尝试以下复利的Python代码:

p = float(input('Please enter principal amount:'))
t = float(input('Please enter number of years:'))
r = float(input('Please enter rate of interest:'))
n = float(input('Please enter number of times the interest is compounded in a year:'))
a = p*(1+(r/(100*n))**(n*t))
print('Amount compounded to: ', a)

相关问题 更多 >