这是一本书中的简单练习,它要求我们确定在给定的利率下金额加倍需要多长时间。我的代码是这样的:
def main():
x = eval(raw_input("Initial Principal: "))
y = eval(raw_input("Interest rate: "))
count = 0
while x < 2*x:
x = x * (1 + y)
count = count + 1
print (x)
print (count)
main()
它返回的是:
Initial Principal: 1000
Interest rate: 0.5
inf
1734
我的代码出了什么问题? 我也想知道如果我的金额和兴趣很小,上面的代码是否会起作用,例如amount = 1,利率= 0.05,因为我猜包含一些浮点运算。
谢谢!
答案 0 :(得分:3)
罪魁祸首是你写的:
while x < 2*x:
由于x > 0
,该关系始终为False
,您不将新x
与旧版x
进行比较,您需要进行比较新x
新x
的两倍。
我们可以通过使用存储初始量的变量x0
来有效地解决这个问题:
def main():
x = x0 = eval(raw_input("Initial Principal: "))
y = eval(raw_input("Interest rate: "))
count = 0
while x < 2*x0:
x = x * (1 + y)
count = count + 1
print (x)
print (count)
main()
但是代码仍然存在一些问题。例如,您使用eval
。不要使用eval
,除非你绝对必须:现在一个人可以输入任何类型的Python代码,也可以输入破坏系统的代码。请使用float(..)
将str
转换为int
:
def main():
x = x0 = float(raw_input("Initial Principal: "))
y = float(raw_input("Interest rate: "))
count = 0
while x < 2*x0:
x = x * (1 + y)
count = count + 1
print (x)
print (count)
main()
但现在代码仍然效率低下。存在使用对数计算年数的快速方法:
from math import log, ceil, pow
def main():
x = x0 = float(raw_input("Initial Principal: "))
y = float(raw_input("Interest rate: "))
count = ceil(log(2.0, y+1.0))
newx = x * pow(1.0+y, count)
print (newx)
print (count)
答案 1 :(得分:2)
问题在于你的守卫,它会检查数字是否少于两次。要解决此问题,请在循环之前保存要在变量中到达的阈值,并且已完成:
threshold = 2 * x
count = 0
while x < threshold:
x = x * (1 + y)
count = count + 1