如何使用 while 循环 c++ 计算输入值?

How to calculate inputted values using a while loop c++?

如何仅使用 while 循环 将多个值与给定点相加,何时退出循环并显示统计金额。

注意下面的例子。 通过输入 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;
}

如何存储一个值,然后重复添加该值,直到程序达到根据计数值退出的点

逻辑解释

  • 在循环外初始化totalCalories0这是防止 undefined behaviour. You may refer to (Why) is using an uninitialized variable undefined behavior? and Default variable value 所必需的。
  • 对于每个项目,将 caloriesForItem 添加到 totalCalories如果您熟悉+= operator,您也可以使用它。

源代码

#include <iostream>

using namespace std;

int main()
{
    int numberOfItems;
    int count = 1; //loop counter for the loop
    int caloriesForItem;
    long totalCalories = 0;
    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 = totalCalories + caloriesForItem;
        ++count;
    }
    cout << "Total calories eaten today  = " << totalCalories;

    return 0;
}

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

totalCalories += caloriesForItem;

你应该增加每个循环的总卡路里数。您可以使用加法赋值运算符 (+=) 轻松地做到这一点。它应该看起来像这样:

totalCalories += caloriesForItem;