2015-01-10 120 views
0

我真的很新,編程和這個代碼只是逗我。For循環不能正常工作

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.我做錯了什麼?

謝謝你的時間看着我愚蠢的問題。

感謝您的回答和耐心等待!我從未擅長數學。

+0

嗯,這是在做你的代碼說什麼。 '餘額=(收入*月) - 花費' – Lack

+8

這不是for循環,而是計算。 –

回答

0

改爲餘額應該等於month*(income-spend)。你現在正在計算當月的總收入,並減去你只花了一個月的時間。你只能節省你作爲收入得到多少和你花多少錢之間的差異,所以你乘以節省的多少乘以你的答案。

1

正如其他人所說,這不是for循環是錯誤的,而是你的計算。更改for循環:

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

另一種解決方案是保持運行總和:

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