我试图运行这个程序,让它为我的函数接受3个参数,并使用它计算复合利息在一段时间内,然后计算和显示的总和在时间周期结束。
这是我的密码:
principal=float(input("Enter an initial principal value: "))
interest=float(input("Enter an interest rate: "))
years=int(input("enter how many years it will take: "))
def payment(principal, interest, years):
n=principle*((1+interest)**years)
for n in range(principal,total):
print(n)
total=n+total
payment(principal, interest, years)我在这个模型中遇到的问题是,它给了我一个错误:
for n in range(principal,total):
TypeError: 'float' object cannot be interpreted as an integer此外,我不太确定它是否会将每个时期的利息复合起来,并在计算下一年的复合利息时将其加到本金中。
发布于 2015-03-08 01:20:12
试一试:
def payment(principal, interest, years):
for period in range(years):
total = float(principal) * float((1+interest)**float(period+1))
print 'Period:', period+1
print 'Total:', total
return total发布于 2015-03-08 01:18:49
范围必须使用整数。请参阅此链接http://www.pythoncentral.io/pythons-range-function-explained/
发布于 2015-03-08 02:27:21
python中的范围接受开始、停止和步骤的整数值。按照医生的说法
这是一个通用的函数,用于创建包含算术进度的列表。它最常用于for循环。参数必须是纯整数。
https://docs.python.org/2/library/functions.html#range
当你说
for n in range(principal,total):
print(n)
total=n+total您将浮点值传递给range函数。另外,如果计划每年打印总计,那么使用for循环的方式是不正确的。如果原理和总和是整数,比如(100,200),它就会把值设为101,102等等。代码除了给你每年的细分之外,还做了一些事情。
下面的代码应该可以帮助您做您想做的事情
''
Let i be in percentage
'''
def computeCompound(s,i):
v = s
while True:
v = v*(1.0 + float(i)/100)
yield v
c = computeCompound(100,20)
for period in range(1,4):
print period
print c.next()https://stackoverflow.com/questions/28921999
复制相似问题