如何编写一个递归函数来计算几年后的硬币净值



我有一个工作代码,尽管有些东西我无法理解。

def stonks(coins, rate, years):
"""
Each year your crypto-investment grows.
Write a recursive function that calculates the net worth of coins after some years.
Rate is in percents.
Round the answer down to the nearest integer.
stonks(1000, 10, 10) -> 2593
stonks(100000, 12, 3) -> 140492
:param coins: starting amount (0-100000)
:param rate: starting amount (0-100)
:param years: starting amount (0-50)
:return: coins after years
"""
if years is not 0:
return stonks((coins * (1 + rate / 100)), rate, years - 1)
else:
return coins

预期输出:

print(stonks(1000, 10, 10))  # -> 2593
print(stonks(100000, 12, 3))  # -> 140492

我的输出:

print(stonks(1000, 10, 10))  # -> 2593.742460100001
print(stonks(100000, 12, 3))  # -> 140492.80000000005

如果我加上math.floor(硬币*(1+rate/100((->我的输出:

print(stonks(1000, 10, 10))  # -> 2591 --- incorrect, needs to be 2593.
print(stonks(100000, 12, 3))  # -> 140492 --- correct

怎么可能,其中一个输出从140492.80000000005到140492被正确地底置,但另一个输出2593.742460100001被错误地底置到2591?

这是因为递归计数更大,因此math.floor应用于递归的每个事件,从而导致最终输出关闭吗?

您可以简单地执行return stonks((coins * (1 + rate / 100)), rate, years - 1) // 1

最新更新