【问题标题】:Removing the loops (for, while) in Python在 Python 中删除循环(for、while)
【发布时间】:2022-07-21 00:16:19
【问题描述】:

有一个代码计算多少年后存款金额将达到目标金额,同时考虑到指定的利率(小数部分被丢弃)。

deposit_amount = int(input('Input deposit amount: '))
annual_percentage = int(input('input annual percentage: '))
final_amount = int(input('Input final amount: '))
year = 0

while deposit_amount < final_amount:
  year += 1
  deposit_amount = deposit_amount * (100 + annual_percentage) // 100

print('After', year, 'years the amount will be:', deposit_amount)

问题:如何在不使用循环的情况下解决相同的问题?他们提示您可以使用“数学”库。

【问题讨论】:

  • 在使用 math 库实现公式之前,只需使用简单的数学(代数)即可。
  • 只需使用复利公式:A = P(1 + r / n ) nt,其中A 是最终金额,P 是初始本金,r 是年利率,n 是每年的复利期数,t 是年数。正如 Julien 所说,只需使用普通代数即可。

标签: python math


【解决方案1】:

@julien 和 @accdias 谢谢!

一切都会好起来的,但是根据问题的情况,答案不应该是总和,在n之后的周期数,而是周期数(n)。在学习复利时,我遇到了对数,并使用数学库解决了这个问题。很可能,我的老师正是这个决定:

deposit_amount = int(input('Input deposit amount: '))
annual_percentage = int(input('input annual percentage: '))
final_amount = int(input('Input final amount: '))

years = ceil(log(final_amount / deposit_amount, annual_percentage))

print('After', years, 'years, your investments will reach the goal and amount to', 
      round(deposit_amount * annual_percentage**years), 'coins.')

【讨论】:

    猜你喜欢
    • 2022-10-20
    • 2016-06-07
    • 2020-10-09
    • 2012-09-19
    • 2014-03-22
    • 1970-01-01
    • 2022-06-28
    • 2021-11-24
    • 2014-09-02
    相关资源
    最近更新 更多