For循环工作不正常

2024-04-25 12:50:50 发布

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

我真的,真的是编程新手,这段代码只是在逗我。你知道吗

def run():
    print('Please enter how many month you want to calculate.')
    month = int(sys.stdin.readline())
    print('Please enter how much money you earn every month.')
    income = int(sys.stdin.readline())
    print('Please enter how much money you spend each month.')
    spend = int(sys.stdin.readline())
    month = month + 1       
    for month in range(1, month):
        balance = (income * month) - spend
        print('The next month you will have %s.' % balance)

我试着做一个小程序来计算你每个月挣多少钱,但是输出的不是我想要的!你知道吗

    >>> run()
Please enter how many month you want to calculate.
5
Please enter how much money you earn every month.
100
Please enter how much money you spend each month.
50
The next month you will have 50.
The next month you will have 150.
The next month you will have 250.
The next month you will have 350.
The next month you will have 450.

似乎,它只提取第一次运行时的花费。其他几个月只是增加了100个。我做错什么了?你知道吗

谢谢你花时间看我愚蠢的问题。你知道吗

谢谢你的回答和耐心!我数学一向不好。你知道吗


Tags: theyouhavesyswillhownextint
3条回答

另一种解决方案是保持运行总数:

balance = 0
for month in range(1, month):
    balance += income
    balance -= spend
    print...

余额应该等于month*(income-spend)。现在你计算的是这个月的总收入,减去你一个月的花费。你只会把你的收入和你的消费之间的差额存起来,所以把这个月乘以你的储蓄,你就得到了答案。你知道吗

正如其他人所说,错误的不是for循环,而是你的计算。将for循环更改为:

for month in range(1, month):
    balance = month *(income - spend)
    print('The next month you will have %s.' % balance)

相关问题 更多 >