简体   繁体   English

For循环无法正常工作

[英]For loop is not working properly

I am really, really new to programming and this code is just teasing me. 我真的是编程新手,这段代码只是在逗我。

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)

I try to make a small program to calculate how much money you earn wach month, but the output is not like I want it! 我尝试制作一个小程序来计算您每个月能赚多少钱,但输出却不是我想要的!

    >>> 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.

It seems, that it only withdraw the amount spend first time it runs. 看来,它仅在第一次运行时提取支出金额。 The other months it is just adding 100. What am I doing wrong? 其他几个月只增加了100。我在做什么错?

Thank you for your time looking at my silly question. 谢谢您抽出宝贵的时间查看我的愚蠢问题。

Thanks for the answers and your patience! 感谢您的回答和耐心等待! I have never been good at math. 我从不擅长数学。

As others have said, it's not the for loop that's wrong, but your calculation. 正如其他人所说,不是for循环是错误的,而是您的计算。 Change the for loop to: 将for循环更改为:

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

The balance should equal month*(income-spend) instead. 余额应等于month*(income-spend) Right now you're calculating the total income up to the month and subtracting how much you spent for one month only. 现在,您要计算到一个月的总收入,然后减去仅一个月的支出。 You only save the difference between how much you get as income and how much you spend, so multiply the month by how much you save and you get your answer. 您只能节省收入和支出之间的差额,因此,将月份乘以您节省的金额即可得到答案。

An alternative solution is to keep a running total: 另一种解决方案是保持总计:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM