使用 while 循环计算何时将金额翻倍


这是

一本书中的一个简单的练习,它要求我们确定在给定利率下金额翻倍需要多长时间。我的代码是这样的:

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

我的代码有什么问题?我也想知道如果我的金额和利息很小,上面的代码是否有效,例如金额 = 1 和利率 = 0.05,因为我想会包含一些浮点运算。

谢谢!

罪魁祸首是你写:

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)

问题是你的 while guard,它会检查数字是否小于自身两倍。要解决此问题,请在循环之前将要达到的阈值保存在变量中,并且您已经完成了:

threshold = 2 * x
count = 0
while x < threshold:
    x = x * (1 + y)
    count = count + 1

最新更新