2014-06-17 50 views
-5

我不能完全弄清楚這個while循環。我瞭解這個概念,我只是不知道該怎麼增加它。另外,由於某種原因,我的跑步總數不起作用?while循環不起作用,如果沒有更改終止它

這背後的想法是設置一個錢儲存在一個罐子的目標。每次我在罐子裏放入一定數量的金錢時,我都希望它能給我罐子裏的所有金錢,並告訴我需要多少錢才能放入罐子才能達到我的目標。

這裏是我的代碼:

#include <stdio.h> 

int main() { 

    int goal; 
    int total = 0; 
    int deposite; 
    int ammountNeeded; 

    printf("How much money would you like to save?\n "); 
    scanf("%i", &goal); 
    printf("How much money are you putting in the jar?\n"); 
    scanf("i%", &deposite); 

    total = total + deposite; 
    ammountNeeded = goal - deposite; 

    while (goal > total) { 
     printf("How much money are you putting in the jar?\n "); 
     scanf("i%", &deposite); 
     printf("You have saved R%i. ", total); 
     printf("You need to save another R%i in order to reach your goal.\n ",ammountNeeded); 
    } 

    if (total >= goal) { 
     printf("Well done! you have sucsessfully saved R%i", goal); 
    } 

    return 0; 
} 
+0

此代碼既不是C#,目標C,或C++。只應用實際有效的標籤。 –

+0

您需要將'deposite'添加到'total'並將其存回'total',否則值永遠不會改變,循環也不會退出,正如您所觀察的那樣。 – aglasser

+0

我看到幾個拼寫錯誤。我沒有看到'while'循環內'total'或'ammountNeeded' [sic]的調整。切勿使用'scanf'。 – zwol

回答

3

while循環有一個條件。只要條件成立,它就會執行身體。在你的情況下,條件不會改變,因爲兩個變量比較沒有一個在循環內改變它的值。你應該增加總數或減少目標。

0

這應該修復它:

while (goal > total) { 
    printf("How much money are you putting in the jar?\n "); 
    scanf("i%", &deposite); 
    total = total + deposite; //Add this 
    printf("You have saved R%i. ", total); 
    ammountNeeded = goal - total; // And perhaps add this 
    printf("You need to save another R%i in order to reach your goal.\n ",ammountNeeded); 

}