2016-03-20 5 views
0

質問: 今日食べた食べ物の数を入力してから各項目のカロリー数を入力するようにユーザーに求めるプログラムを作成します。その後、その日に食べたカロリーの数を計算し、その値を表示します。カロリー計数ループ

最終的には、whileループでなければならないと言いますが、どのように読んで計算するのかはわかりません。

答えて

0

あなたはすでにすべての作品を持っています。あなたのループにはcounttotalCaloriesトラッカー、そして現在のアイテムを保持する変数caloriesForItemがあります。ループの繰り返しごとにcountを増やす必要があり、すべての反復でcaloriesForItemの新しい値を取得する必要があります。これを毎回totalCaloriesに追加できます。

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ループはこのthemplateを使用して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++; 
} 
なり