繁体   English   中英

For循环无法正常工作

[英]For loop is not working properly

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

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。我在做什么错?

谢谢您抽出宝贵的时间查看我的愚蠢问题。

感谢您的回答和耐心等待! 我从不擅长数学。

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

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

余额应等于month*(income-spend) 现在,您要计算到一个月的总收入,然后减去仅一个月的支出。 您只能节省收入和支出之间的差额,因此,将月份乘以您节省的金额即可得到答案。

另一种解决方案是保持总计:

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