C++ 如何为每个循环添加变量值?(使用C+;+;。阅读更多信息)

C++ 如何为每个循环添加变量值?(使用C+;+;。阅读更多信息),c++,C++,我有一个“For循环”,其中有一个变量作为“itemPrice”,它是一个变量,它是用户输入的值(“cin>>itemPrice;”代码也在下面)。“For循环”外部的变量称为“totalPrice”,每次从“itemPrice”输入价格并将其添加到上一个价格时,我都需要它,依此类推,直到用户完成添加。有人知道怎么做吗?我的脑子快炸了,因为我不知道怎么做 以下是我尝试执行的代码块: for(itemNumber = 0; itemNumber < 30; itemNumber++){

我有一个“For循环”,其中有一个变量作为“itemPrice”,它是一个变量,它是用户输入的值(“cin>>itemPrice;”代码也在下面)。“For循环”外部的变量称为“totalPrice”,每次从“itemPrice”输入价格并将其添加到上一个价格时,我都需要它,依此类推,直到用户完成添加。有人知道怎么做吗?我的脑子快炸了,因为我不知道怎么做

以下是我尝试执行的代码块:

for(itemNumber = 0; itemNumber < 30; itemNumber++){
   cout <<"Please input item price of item of #:"<< itemNumber << endl;
   cout <<"(if You are finished enter 00.)"
   cin >> itemPrice;

   if(itemPrice == 00)
   {
     break;
   }
}

totalPrice //Here I want to add it to this variable for every previous value
           //of 'itemPrice' that entered adds it to the previouse value, and
           //so on.
for(itemNumber=0;itemNumber<30;itemNumber++){

cout您可以在for loop中告诉我们总价,并将值设置为

totalprice=itemprice+totalprice;

然后您可以打印出循环外总价的最终值

您描述的问题非常简单。我不知道您不清楚如何解决这个问题:

double itemPrice = 0.0;
double totalPrice = 0.0; // <<<<<<<<<<<<<<
for(itemNumber = 0; itemNumber < 30; itemNumber++){
   cout <<"Please input item price of item of #:"<< itemNumber << endl;
   cout <<"(if You are finished enter 00.)"
   cin >> itemPrice;

   if(itemPrice == 00) // <<<< This might be problematic, but not for an input of 0
   {
     break;
   }
   totalPrice += itemPrice; // <<<<<<<<<<<<<<<<<<<
}

std::cout << "Total: " << totalPrice << std::endl;
double itemPrice=0.0;
double totalPrice=0.0;//
int totalPrice=0;
对于(itemNumber=0;itemNumber<30;itemNumber++){

难道这不是家庭作业……这是一种练习,我想到了这个主意。我需要去做@SamVarshavchik@SamVarshavchik这有什么关系吗?这个问题很糟糕。@hellzyeah尝试了类似于
total+=itemPrice
?@hellzyeah正确初始化所有变量。我真的不明白你的问题是什么。请参阅我的a中的代码nswer.
cin>>itemPrice
不区分
00
0
-两者都是0。这很有效!Holycrap伙计!你需要奖励什么的,我希望我能给你一些回报。:D你最好。@Hellzyeah“你最好”当然不是。我只是另一个咖啡迷。我不在乎。你只是创造了一个人日,激励我成为像你一样聪明的人,我尊敬像你这样的人。你做了一些只有像我这样的傻瓜才会真正欣赏的事情。我在谷歌上搜索了这个问题,并尝试了研究,但没有找到答案,也不是重复的问题。朋友,如果有人我没告诉你,坚持下去。
    int totalPrice = 0;
 for(itemNumber = 0; itemNumber < 30; itemNumber++){
    cout <<"Please input item price of item of #:"<< itemNumber << endl;
    cout <<"(if You are finished enter 00.)"
    cin >> itemPrice;
    totalPrice+=itemPrice;
    if(itemPrice == 00)
    {
      break;
    }
 }

cout<<totalPrice;