c++ 中的变量可以将旧值加上新值吗?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7626929/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Can a variable in c++ add its old value plus its new value?
提问by user975452
Is there a way in c++ for a single variable to maintain its same value and when added to, it will add its last value with the new one? for example, I am writing a program where the user can enter as many "checks" and "deposits" they received through the day, and at the end of the day the program will let the user know how much he made throughout the day
c++ 中是否有一种方法可以让单个变量保持其相同的值,并且在添加时,它会将其最后一个值与新值相加?例如,我正在编写一个程序,用户可以输入他们当天收到的尽可能多的“支票”和“存款”,并且在一天结束时,该程序将让用户知道他一整天赚了多少钱
here is what I have so far
这是我到目前为止所拥有的
#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
the problem is that i need the variable "check" and "depo" to be able to add the users first value and the second value to get the new value. right now all it does is display the last value the user inserted.
问题是我需要变量“check”和“depo”才能添加用户的第一个值和第二个值以获得新值。现在它所做的就是显示用户插入的最后一个值。
回答by Nawaz
Yes.
是的。
You can add new values to old value as:
您可以将新值添加到旧值,如下所示:
oldValue += newValue;
Or alternatively, you can also do this:
或者,您也可以这样做:
oldValue = oldValue + newValue;
回答by shubhendu mahajan
A variable can only display the last value the user inserted.suppose
变量只能显示用户插入的最后一个值。假设
int a=5;
a=a+5;
cout<<a;
the output will be 10
as the new value overwrites the previous one at the address of a.
在output will be 10
为新的值覆盖在一个地址的前一个。