Python:将您上次的答案乘以一个常数

3

我正在尝试展示特定年数内,随着每年增加的百分比,薪水的变化。

print('Enter the strting salary: ', end ='')
SALARY = float(input())
print('Enter the annual % increase: ', end ='')
ANNUAL_INCREASE = float(input())

calculation1 = ANNUAL_INCREASE / 100
calculation2 = calculation1 * SALARY
calculation3 = calculation2 + SALARY



Yearloops = int(input('Enter number of years: '))

for x in range(Yearloops):
    print(x + 1, calculation3 )

在将工资设为25000元、涨幅设为3%、年数设为5年后,这是我的输出结果。

1 25750.0
2 25750.0
3 25750.0
4 25750.0
5 25750.0

我需要再次将上一个答案乘以增加的百分比。应该像这样:
1 25000.00 
2 25750.00 
3 26522.50
4 27318.17 
5 28137.72

有人可以展示给我如何做吗?谢谢。

4个回答

1
你需要将计算放在for循环内部,这样它才会每年发生一次,而不仅仅是一次。
salary = float(input('enter starting salary: '))
annual_increase = float(input('enter the annual % increase: '))
years = int(input('enter number of years: '))

for x in range(years):
    print(x + 1, salary)

    increase = (annual_increase/100) * salary
    salary += increase

输入25000、3%和5年,输出:
1 25000.0
2 25750.0
3 26522.5
4 27318.175
5 28137.72025

0

稍微修改一下您代码的版本:

print('Enter the strting salary: ', end ='')
SALARY = float(input())
print('Enter the annual % increase: ', end ='')
ANNUAL_INCREASE = float(input())

Yearloops = int(input('Enter number of years: '))

value = SALARY
for x in range(Yearloops):
    print('{} {:.2f}'.format(x + 1, value))
    value = value * (1 + ANNUAL_INCREASE/100)

使用测试用例25000、3、5将产生以下输出:

Enter the strting salary: 25000
Enter the annual % increase: 3
Enter number of years: 5
1 25000.00
2 25750.00
3 26522.50
4 27318.17
5 28137.72

0

我觉得这个会满足你的需求:

print('Enter the strting salary: ', end ='')
SALARY = float(input())
print('Enter the annual % increase: ', end ='')
ANNUAL_INCREASE = float(input())

calculation1 = ANNUAL_INCREASE / 100

Yearloops = int(input('Enter number of years: '))

newsalary = SALARY
print(1, newsalary )
for x in range(1,Yearloops):
    newsalary = newsalary*(1+calculation1)
    print(x + 1, newsalary )

我在循环外打印了第一年,因为根据您的规格,我们还不想计算增长。


0

这似乎是一个相当直接的解决方案,供您参考:当您不打算使用正在迭代的项时,通常会使用for _ in something

print('Enter the starting salary: ', end ='')
SALARY = float(input())
print('Enter the annual % increase: ', end ='')
ANNUAL_INCREASE = float(input())

Yearloops = int(input('Enter number of years: '))

for _ in range(Yearloops):
    print(SALARY)
    SALARY += (SALARY / 100) * ANNUAL_INCREASE

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接