2016-03-20 38 views
0

問題: 創建一個程序,首先要求用戶輸入他/她今天吃過的物品數量,然後輸入每個物品的卡路里數。然後計算他/她在當天進食的卡路里數並顯示該值。卡路里計數循環

#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循環。

回答

0

你已經擁有了所有的作品。您有一個count爲您的循環,一個totalCalories跟蹤器和一個變量來保存當前項目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循環到while循環中使用該themplate:

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++; 
}