提问人:HW19 提问时间:10/28/2023 更新时间:10/28/2023 访问量:42
返回值不匹配循环
return value not matching loop
问:
我的代码被拆分为两个 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
R1T系列
# 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
答:
1赞
DarkFranX
10/28/2023
#1
就像 John 在评论中所说的那样,您需要重新设计打印编排:
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
您希望在修改值后进行打印。为此,请为初始值添加初始 print(),然后反转 for 中的操作顺序。圈。注意将循环计数减少 1,并在循环内将索引偏移 +1。
评论
final_value