卡路里计数循环

时间:2016-03-20 20:33:02

标签: c++ while-loop

问题: 创建一个程序,首先要求用户输入他/她今天吃过的物品数量,然后输入每个物品的卡路里数量。然后计算他/她当天吃的卡路里数量并显示该值。

#include <iostream>
using namespace std;
int main()
{
    int numberOfItems;
    int count; // 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 (caloriesForItem)
    {
        cout << "Please enter item calories:";
        cin >>caloriesForItem;
        count == numberOfItems;

    }


    cout << "Total calories eaten today = " << totalCalories;
    return 0;
}

最后我不知道如何让它读取和计算,因为它说它必须是一个while循环。

3 个答案:

答案 0 :(得分:0)

你已经拥有了所有作品。您的循环有counttotalCalories跟踪器和保存当前项caloriesForItem的变量。循环的每次迭代都必须增加count,并且每次迭代都必须为caloriesForItem检索新值。您每次都可以将此添加到totalCalories

答案 1 :(得分:0)

#include <iostream>

using namespace std;

int main()
{
    int numberOfItems;
    int caloriesForItem;
    // These two variables need to have a start value
    int count = 0;
    int 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;

    // Loop for as many times as you have items to enter
    while (count < numberOfItems)
    {
        cout << "Please enter item calories:";
        // Read in next value
        cin >> caloriesForItem;
        // Add new value to total
        totalCalories += caloriesForItem;
        // Increase count so you know how many items you have processed.
        count++;
    }

    cout << "Total calories eaten today = " << totalCalories;
    return 0;
}

你很亲密 (我在适当的地方添加了评论来解释发生了什么。)

最后,我想补充说,您几乎可以使用此模板将任何for循环转换为while循环:

for( <init_var>; <condition>; <step> ) {
  // code
}

变为

<init_var>;

while( <condition> ) {
  // code

  <step>;
}

示例:

for(int i = 0; i < 10 i++) {
  cout << i << endl;
}

变为

int i = 0;

while(i < 10) {
  cout << i << endl;

  i++;
}

答案 2 :(得分:0)

看一下这段代码:

#include <iostream>
using namespace std;
int main()
{
    int numberOfItems, caloriesForItem, 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 (numberOfItems--)
    {
        cout << "Please enter item calories:";
        cin >> caloriesForItem;
        totalCalories += caloriesForItem;
    }

    cout << "Total calories eaten today = " << totalCalories;
    return 0;
}

这是完成您想要的事情的一种充分方法,如果您不了解,请告诉我!