所以我正在为大学作业,对编码还很陌生,所以这里有一个问题。在一所大学,全日制学生的学费为每学期 8,000 美元。据宣布,未来五年学费将每年增加3%。编写一个带有循环的程序,该循环"显示未来五年的预计学期学费金额。
tuition_increase = 0.03
tuition = 8000
tuition_total = 0
years = 5
print('tuition_totaltyears')
print('--------------------')
for years in range (1, years + 1)
tuition_total = (tuition * tuition_increase) + tuition
print(tuition_total, '/t', years)
我一遍又一遍地获得相同的价值,而不是随着每年学费的增加而增加
您不会tuition_total
值总和到上一步计算tuition_total
值,请尝试以下方法。
tuition_total = ((tuition * tuition_increase) + tuition) + tuition_total
或
tuition_total += (tuition * tuition_increase) + tuition
你不需要tuition_total
只是分配回tuition
,例如:
In []:
tuition_increase = 0.03
tuition = 8000
years = 5
print('tuitiontyears')
print('--------------------')
print(tuition, 't', 0)
for years in range (1, years + 1):
tuition *= (1+tuition_increase)
print(tuition, 't', years)
Out[]:
tuition years
--------------------
8000 0
8240.0 1
8487.2 2
8741.816 3
9004.07048 4
9274.1925944 5
如您所见,您将需要修复格式。
您还可以使用itertools.accumulate()
执行以下操作:
In []:
tuition_increase = 0.03
tuition = 8000
years = 5
print('{:10}{}'.format('tuition', 'years'))
print('-'*20)
for year, tuition in enumerate(it.accumulate(it.repeat(tuition, years+1), lambda x, y: x*(1+tuition_increase))):
print('{:<10.2f}{}'.format(tuition, year))
Out[]:
tuition years
--------------------
8000.00 0
8240.00 1
8487.20 2
8741.82 3
9004.07 4
9274.19 5
需要做一些小的改变。
tuition_increase = 0.03
tuition = 8000
tuition_total = 0
years = 5
print('tuition_totaltyears')
print('--------------------')
for years in range (1, years + 1):
tuition = (tuition * tuition_increase) + tuition
print(tuition, '/t', years)
这是更正的一个。for
后的第一行是计算复利的正确公式。请注意,我从零开始为它编制索引年份。
print()
更改为使用.format()
以获得表格输出。
tuition_increase = 0.03
tuition = 8000
tuition_total = 0
years = 5
print('tuition_totaltyears')
print('--------------------')
for years in range (0, years ):
tuition_total = tuition * (1+tuition_increase)** years
print('{0:<15} {1}'.format(int(tuition_total), years+1))
将打印
tuition_total years
--------------------
8000 1
8240 2
8487 3
8741 4
9004 5
以下是Tony Gaddis的书《Start out with Python》(Pearson Revel)中建议的解决方案:
tuition = 8000
for i in range(1, 6):
tuition *= 1.03
if i == 1:
print("In 1 year, the tuition will be $" + str(tuition) + ".")
else:
print("In "+str(i)+" years, the tuition will be $" + str(tuition) + ".")
这是我如何做到并做对的。
tuition = 8240.00
tuition1 = 8000
rate = 0.03
for year1 in range(1, 2):
tuition1 = tuition1 * (1 + rate)
print(f"In {year1} year, the tuition will be ${tuition1:.2f}.")
for year in range (2, 6):
tuition *= (1 + rate)
print(f"In {year} years, the tuition will be ${tuition:.2f}.")
我正在做我的代码,假设大学一年有 3 个学期,这是典型的。
tuition = 8000 * 3
for x in range(1, 6):
tuition *= 1.03
if x == 1:
print("In 1 year, the tuition will be $" + str((" %.2f" %tuition) + "."))
else:
print("In "+str(x)+" years, the tuition will be $" + str((" %.2f" %tuition) + "."))