2011-10-02 97 views
-2

是否有一種方法在c + +單個變量保持其相同的價值,並添加到,它會添加新的最後一個值?例如,我正在編寫一個程序,用戶可以輸入他們在一天中收到的許多「支票」和「存款」,並且在一天結束時,程序會讓用戶知道他一天中賺了多少錢C++中的變量是否可以添加舊值加上新值?

這裏是我迄今爲止

#include <cstdlib> 
#include <iostream> 

using namespace std; 

int main(int argc, char *argv[]) 
{ 

system("Color 0E"); 
int cashBalance = 1000; 
int check; 
int depo; 
double toDepo = depo * 0.3; 
double totalDepo = depo - toDepo; 
int loop = 5; 
int choice; 

cout << "check = 1, deposit = 2, add = 3, clear the screen = 4, close = 0\n" << endl; 
while (loop == 5){ 
    cout << "Would you like to enter a depoist or a check?\n" << endl; 
    cin >> choice; 
    //determines whether or not to close the program 
    if(choice == 0 || depo == 0 || check == 0){ 
    return 0;   
    }//end close if 
    //choses which type of input to make 
    if(choice == 1){ 
     cout << "Please enter check\n" << endl;  
     cin >> check; 
    } else if(choice == 2){ 
     cout << "Please enter deposit\n" << endl; 
     cin >> depo; 
    }//end if 
    if(choice == 3 || depo == 3 || check == 3){ 
    cout << "Total = " << (cashBalance - check) + totalDepo << endl; 
    } 
    //clear the console screen 
    if(choice == 4 || depo == 4 || check == 4){ 
    system("cls"); 
    cout << "check = 1, deposit = 2, add = 3, clear the screen = 4, close = 0\n" << endl; 
    } 
}//end while loop 
system("PAUSE"); 
return EXIT_SUCCESS; 
}//end of program 

的問題是,我需要的變量「檢查」和「帝寶」才能夠添加用戶第一值和第二值來獲得新的值。現在它所做的只是顯示用戶插入的最後一個值。

回答

7

是的。

您可以爲舊值添加新值:

oldValue += newValue; 

或者,你也可以這樣做:

oldValue = oldValue + newValue; 
+0

將「newValue」是一個全新的變量,或者它將是例如檢查+ =檢查; – user975452

+0

@ user975452:如果你寫'check + = check',它不會自己添加到它嗎?這相當於'check = check + check',這相當於'check = 2 * check'。那麼新的價值儲存在哪裏,舊的價值在哪裏?自己提出這些問題。 – Nawaz

3

變量只能顯示最後一個值的用戶inserted.suppose

int a=5; 
a=a+5; 
cout<<a; 

output will be 10由於新值會覆蓋廣告中的前一個值一件衣服。

相關問題