在c ++中是否有一种方法可以使单个变量保持相同的值,并且在添加时,它会使用新值添加其最后一个值? 例如,我正在编写一个程序,用户可以在该程序中输入他们当天收到的“支票”和“存款”,并且在一天结束时程序将让用户知道他一整天都在做多少< / p>
这是我到目前为止所拥有的
#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
问题是我需要变量“check”和“depo”才能添加用户的第一个值和第二个值来获取新值。现在它只是显示用户插入的最后一个值。
答案 0 :(得分:7)
是
您可以将旧值添加到旧值中:
oldValue += newValue;
或者,您也可以这样做:
oldValue = oldValue + newValue;
答案 1 :(得分:3)
变量只能显示用户insert.suppose
的最后一个值int a=5;
a=a+5;
cout<<a;
output will be 10
,因为新值会覆盖前一个地址。