如何正确循环这个乘法?

2024-09-25 00:33:29 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图计算一个物体在20年内的折旧,每年按其原值的15%计算。问题是它只将第一次乘法的结果减去循环的其余部分,而不是将值减少15%20倍

ovalue = int(input("Enter the value of the car: "))
res = ovalue * 0.15
fvalue = ovalue - res
year = 1
while (year <= 20):
   print("Year ",year,":", fvalue)
   year = year+1
   fvalue = fvalue-res

有办法解决这个问题吗?多谢各位


Tags: oftheinputvaluerescaryear物体
3条回答
price = []
for i in range(1,20):
    value -= value*0.15
    price.append(value)

这将在每次迭代中将该值减少当前值的15%

value = int(input("Enter the value of the car: "))

year = 1
while year <= 20:
   value -= value * 0.15
   print("Year ",year,":", value)
   year = year+1

这将在每次迭代时将值减少原始值的15%(这可能不是您想要的)

value = int(input("Enter the value of the car: "))

deduction = value * 0.15
year = 1
while year <= 20:
   value -= deduction
   print("Year ",year,":", value)
   year = year+1

正如许多人所说,你想乘以折旧值。注意,如果它贬值15%,它的新值将是当前值的85%。因为这是乘法,所以我们可以使用幂

def depreciate(initialValue, depreciationRate, numYears):
    depreciationRate = 1 - depreciationRate
    return initialValue * (depreciationRate ** numYears)

相关问题 更多 >