はじめに
この実験では、C++ で配列を使わずにユーザーが入力した n 個の数の平均を計算する方法を学びます。コードを 1 行ずつ見て、それがどのように機能するかを理解します。
ライブラリのインクルードと名前空間の使用
以下のコマンドを使用して、~/project ディレクトリに新しいファイル main.cpp を作成します。
touch ~/project/main.cpp
最初のステップでは、必要なライブラリをインクルードし、標準名前空間を使用します。
#include <iostream>
using namespace std;
歓迎メッセージと変数宣言
次のステップでは、ユーザーに歓迎メッセージを表示し、プログラムで使用する変数を宣言します。
int main()
{
cout << "\n\nWelcome to the Average Calculator!\n\n";
int n, i, temp;
double sum = 0, average = 0;
}
以下の変数を宣言します。
nは、ユーザーが入力する整数の数です。iは、ループ変数です。tempは、ユーザー入力を読み取るための一時変数です。sumは、ユーザーが入力したすべての値の合計を保持します。averageは、合計を n で割って計算されます。
ユーザー入力の読み取り
次のステップでは、ユーザーからの入力を読み取ります。ユーザーに、平均を求めたい整数の数を入力してもらいます。
cout << "Enter the number of integers: ";
cin >> n;
その後、ユーザーに 1 つずつ各数を入力してもらいます。ユーザー入力を取得し、入力された数を合計に加えるために for ループを使用します。
for (i = 1; i <= n; i++)
{
cout << "Enter number " << i << ": ";
cin >> temp;
sum += temp;
}
平均値の計算
これで、入力された数の平均を合計と整数の数を使って計算することができます。
average = sum / n;
平均値をユーザーに出力する
最後のステップは、最終結果をユーザーに出力することです。
cout << "\n\nThe Sum of the " << n << " numbers entered by the user is: " << sum << endl;
cout << "\nThe Average of the " << n << " numbers entered by the user is : " << average << "\n\n";
完全なコード
#include <iostream>
using namespace std;
int main()
{
cout << "\n\nWelcome to the Average Calculator!\n\n";
int n, i, temp;
double sum = 0, average = 0;
cout << "Enter the number of integers: ";
cin >> n;
for (i = 1; i <= n; i++)
{
cout << "Enter number " << i << ": ";
cin >> temp;
sum += temp;
}
average = sum / n;
cout << "\n\nThe Sum of the " << n << " numbers entered by the user is: " << sum << endl;
cout << "\nThe Average of the " << n << " numbers entered by the user is : " << average << "\n\n";
return 0;
}
コードをコンパイルして実行するには、ターミナルで次のコマンドを実行します。
g++ main.cpp -o main
./main
まとめ
この実験では、配列を使わずにユーザーが入力した n 個の数の平均を計算する方法を学びました。for ループを使ってユーザーからの入力を読み取り、入力された数の合計と平均を計算しました。最後に、結果をユーザーに出力しました。



