返回值与循环不匹配

问题描述 投票:0回答:1

我的代码被分成两个 pydev 文件。 Functions.py 和 t12.py。我的问题是,当我调用函数并且 for 循环运行时,循环的最终值和我从 t12 函数调用的值不匹配。我假设循环正在运行额外的时间,这就是为什么我的答案不同

功能

def gic(value, years, rate):

    print(f"\n{'Year':<2}{'Value $':>10s}")
    print("--------------")
    
    final_value = value
    
    for x in range(years + 1):
        print(f"{x:>2}{final_value:>12,.2f}")
        final_value *= (1 + (rate / 100))
        
    return final_value

t12

# Imports  
from functions import gic

# Inputs 
value = int(input("Value: "))
years = int(input("Years: "))
rate = float(input("Rate: "))

# Function calls
final_value = gic(value, years, rate)

print(f"\nFinal value: {final_value:.2f}")

代码输出值(1000,10,5):

Value: 1000
Years: 10
Rate: 5

Year   Value $
--------------
 0    1,000.00
 1    1,050.00
 2    1,102.50
 3    1,157.62
 4    1,215.51
 5    1,276.28
 6    1,340.10
 7    1,407.10
 8    1,477.46
 9    1,551.33
10    1,628.89

Final value: 1710.34

所需输出:

Value: 1000
Years: 10
Rate: 5

Year   Value $
--------------
 0    1,000.00
 1    1,050.00
 2    1,102.50
 3    1,157.62
 4    1,215.51
 5    1,276.28
 6    1,340.10
 7    1,407.10
 8    1,477.46
 9    1,551.33
10    1,628.89

Final value: 1628.89
python function for-loop function-call
1个回答
0
投票

就像约翰在评论中所说,你需要重新设计打印编排:

def gic(value, years, rate):

print(f"\n{'Year':<2}{'Value $':>10s}")
print("--------------")

final_value = value

print(f"{0:>2}{final_value:>12,.2f}")

for x in range(years):
    final_value *= (1 + (rate / 100))
    print(f"{x+1:>2}{final_value:>12,.2f}")
    
return final_value
© www.soinside.com 2019 - 2024. All rights reserved.