【问题标题】:Can a variable in c++ add its old value plus its new value?c++ 中的变量可以添加它的旧值加上它的新值吗?
【发布时间】:2011-10-02 14:23:49
【问题描述】:

在 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

问题是我需要变量“check”和“depo”才能添加用户的第一个值和第二个值以获得新值。现在它所做的只是显示用户插入的最后一个值。

【问题讨论】:

    标签: c++ variable-assignment


    【解决方案1】:

    是的。

    您可以将新值添加到旧值:

    oldValue += newValue;
    

    或者,您也可以这样做:

    oldValue = oldValue + newValue;
    

    【讨论】:

    • would"newValue" 是一个全新的变量还是例如 check += check;
    • @user975452:如果你写check += check,它不会自己加进去吗?它等价于check = check + check,而后者又等价于check = 2 * check。那么新价值存储在哪里,你的旧价值又在哪里呢?自己问这些问题。
    【解决方案2】:

    一个变量只能显示用户最后插入的值。假设

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

    output will be 10 作为新值覆盖 a 地址处的前一个值。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-08-14
      • 2011-07-27
      • 2013-08-28
      • 1970-01-01
      • 1970-01-01
      • 2015-06-14
      • 1970-01-01
      • 2020-12-03
      相关资源
      最近更新 更多