【问题标题】:Computing future value of an account, when the user enters in the present value, interest rate, and number of years当用户输入现值、利率和年数时,计算账户的未来值
【发布时间】:2016-03-04 03:44:53
【问题描述】:

每当我运行它时,它只会继续获得p 值,而不是计算出的帐户未来值?!

def main():
    p=eval(input("Enter in the present value of the account: "))
    i=eval(input("Enter in the monthly interest rate(%): "))
    I=eval(str(i//100))
    t=eval(input("Enter the number of months that that the money will be in the account: "))

    print(futureValue(p, I, t),"Is the future value of your account!")

def futureValue(p, I, t):
    return p*((1 + I) ** t)

main()

【问题讨论】:

  • 对于这一切的热爱是神圣的,不要eval原始用户输入。即使我们忽略整个“安全问题的定义”这件事,它也意味着用户的小错别字可能会以您无法开始预测或处理的方式完成完全出乎意料的事情。如果目标是转换为intfloatdecimal.Decimal,请使用它们的构造函数。如果目标是接受intfloat 或任何其他Python 文字,请使用ast.literal_eval,它接受Python 文字,但不接受任意代码。

标签: python function python-3.x math


【解决方案1】:

这是因为您在i//100 中使用了//,而不是/。这将导致i/100 的结果向下舍入,因此只要i < 100 总是导致0.0(情况就是这样)。这就是为什么你的未来价值总是和现在一样,因为你投入的钱没有利息

简单的改变:

I=eval(str(i//100))

进入:

I=eval(str(i/100))

另外,由于您永远不需要评估I(它只是i/100,您已经从用户输入中获得了evali),请尝试像这样简单地输入I=i/100

def main():
    p=eval(input("Enter in the present value of the account: "))
    i=eval(input("Enter in the monthly interest rate(%): "))
    I=i/100 #simply put this
    t=eval(input("Enter the number of months that that the money will be in the account: "))

    print(futureValue(p, I, t),"Is the future value of your account!")

def futureValue(p, I, t):
    return p*((1 + I) ** t)

main()

你应该得到你的未来价值

【讨论】:

  • 这里重要的变化不是删除eval,而是使用真正的除法(/)而不是地板除法(//);当输入在 0-99 范围内时,后者在除以 100 时将始终产生 0,而前者将产生 0.0-0.99,如您所料。 eval邪恶的,但这不是罪魁祸首。
  • 是的,当您刚刚发表评论时,我正在输入更新。 :)
猜你喜欢
  • 1970-01-01
  • 2021-12-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-06-24
  • 1970-01-01
  • 2022-01-03
  • 2021-12-08
相关资源
最近更新 更多