質問: 今日食べた食べ物の数を入力してから各項目のカロリー数を入力するようにユーザーに求めるプログラムを作成します。その後、その日に食べたカロリーの数を計算し、その値を表示します。カロリー計数ループ
最終的には、whileループでなければならないと言いますが、どのように読んで計算するのかはわかりません。
質問: 今日食べた食べ物の数を入力してから各項目のカロリー数を入力するようにユーザーに求めるプログラムを作成します。その後、その日に食べたカロリーの数を計算し、その値を表示します。カロリー計数ループ
最終的には、whileループでなければならないと言いますが、どのように読んで計算するのかはわかりません。
あなたはすでにすべての作品を持っています。あなたのループにはcount
、totalCalories
トラッカー、そして現在のアイテムを保持する変数caloriesForItem
があります。ループの繰り返しごとにcount
を増やす必要があり、すべての反復でcaloriesForItem
の新しい値を取得する必要があります。これを毎回totalCalories
に追加できます。
#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++;
}
なり