はじめに
この実験では、C++ で配列を使わずにユーザーが入力した n 個の数の平均を計算する方法を学びます。コードを1行ずつ見て、それがどのように機能するかを理解します。
この実験では、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ループを使ってユーザーからの入力を読み取り、入力された数の合計と平均を計算しました。最後に、結果をユーザーに出力しました。