C++ 如何使用while循环c++;?

C++ 如何使用while循环c++;?,c++,while-loop,addition,C++,While Loop,Addition,如何使用while loop only在退出循环并显示计数的金额时,在给定的点上添加多个值 请注意以下示例通过输入项目数7和以下卡路里值来测试您的程序:7-120 60 150 600 1200 300 200 如果您的逻辑正确,将显示以下内容:今天摄入的总热量=2630 下面是我写的,我需要的是理解总热量的计算 #include <iostream> using namespace std; int main() { int numberOfItems; int

如何使用while loop only在退出循环并显示计数的金额时,在给定的点上添加多个值

请注意以下示例通过输入项目数7和以下卡路里值来测试您的程序:7-120 60 150 600 1200 300 200

如果您的逻辑正确,将显示以下内容:今天摄入的总热量=2630

下面是我写的,我需要的是理解总热量的计算

#include <iostream>

using namespace std;

int main()
{
    int numberOfItems;
    int count = 1; //loop counter for the loop
    int caloriesForItem;
    int totalCalories;
    cout << "How many items did you eat today? ";
    cin >> numberOfItems;
    cout << "Enter the number of calories in each of the "
         << numberOfItems << " items eaten:  " << endl;

    while (count <= numberOfItems) // count cannot be more than the number of items
    {
        cout << "Enter calorie: ";
        cin >> caloriesForItem;
        totalCalories = ; //?
        ++count;
    }
    cout << "Total calories  eaten today  = " << totalCalories;

    return 0;
}
#包括
使用名称空间std;
int main()
{
国际项目数;
int count=1;//循环的循环计数器
项目的热量;
总热量;
cout>numberOfItems;
逻辑解释
  • 在循环外部将
    totalcarries
    初始化为
    0
    。这是防止发生错误所必需的。您可以参考和
  • 对于每个项目,将
    caroriesforitem
    添加到
    totalcarories
    中。如果您熟悉,也可以使用
源代码
#包括
使用名称空间std;
int main()
{
国际项目数;
int count=1;//循环的循环计数器
项目的热量;
长期总热量=0;
cout>numberOfItems;
逻辑解释
  • 在循环外部将
    totalcarries
    初始化为
    0
    。这是防止发生错误所必需的。您可以参考和
  • 对于每个项目,将
    caroriesforitem
    添加到
    totalcarories
    中。如果您熟悉,也可以使用
源代码
#包括
使用名称空间std;
int main()
{
国际项目数;
int count=1;//循环的循环计数器
项目的热量;
长期总热量=0;
cout>numberOfItems;

cout也可以用+=运算符添加它们,但结果是一样的

totalCalories += caloriesForItem;

您也可以使用+=运算符添加它们,但结果将是相同的

totalCalories += caloriesForItem;

您应该增加每个循环中的总卡路里数。您可以使用加法赋值运算符(+=)轻松做到这一点。它应该如下所示:

totalCalories += caloriesForItem;

您应该增加每个循环中的总卡路里数。您可以使用加法赋值运算符(+=)轻松做到这一点。它应该如下所示:

totalCalories += caloriesForItem;

为什么“今天摄入的总热量=2631”?它加起来等于
2630
。您可以将
caroriesforitem
的声明移动到
while
循环中,作为第一个语句。这是您可能想要建立的一种实践:声明最接近其第一次使用的变量。此外,该变量仅在
while
循环中使用。@PalLaden 2631是一个错别字,抱歉,我已经在你注意到后纠正了错误。为什么“今天吃的总热量=2631”?它加起来等于
2630
。您可以将
caroriesforitem
的声明移动到
while
循环中,作为第一个语句。这是您可能想要建立的一种实践:声明最接近其第一次使用的变量。此外,该变量仅在
while
循环中使用。@PalLaden 2631是一个错别字,抱歉,在您注意到错误后,我已经纠正了错误。谢谢您@PalLaden,这[int-TotalCarries=0;]起了所有的作用。对于解释原因,我有了更多的良心理解。谢谢您@PalLaden,这[int-TotalCarries=0;]对于解释原因,我有更多的良心理解。