3

私は学校のプロジェクトに取り組んでいます。これが当てはまります:

n人の生徒の重みを入力できるはずです。生徒の平均体重を計算し、体重が65kg未満の生徒の数を出力します。

これで、C++ソースのサンプルができました。

#include <cstdlib>
#include <iostream>

using namespace std;

int main(int argc, char *argv[])
{
    int number_of_students;

    cout << "How many students would you like to add?: ";
    cin >> number_of_students;
    cout << endl;
    cout << endl;

    cout << "--------------------------------------------" << endl;
    cout << "---------- ENTER STUDENT'S WEIGHT ----------" << endl;
    cout << "--------------------------------------------" << endl;
    cout << endl;

    system("PAUSE");
    return EXIT_SUCCESS;
}

私は現在立ち往生しているので、これは基本的に何もありません。ユーザーがたとえば6人の生徒を入力したときに、たとえば6つの新しい重み変数を誰に追加できるかわかりません。

編集:

平均体重を計算して、体重が65kg未満の生徒の数を見つけることができます。追加される生徒の数の変数の数を定義することに固執しているのは私だけです。生徒の平均体重を計算し、体重が65kg未満の生徒の数を出力します。

4

4 に答える 4

6

ウェイトは、サイズが可変のある種のコンテナに保存する必要があります。標準ライブラリのコンテナを使用することを強くお勧めします。最も一般的な選択はstd::vectorです。

#include<vector>
#include<algorithm>  //contains std::accumulate, for calculating the averaging-sum

int main(int argc, char *argv[])
{
    int number_of_students;

    cout << "How many students would you like to add?: ";
    cin >> number_of_students;
    cout << endl;
    cout << endl;

    cout << "--------------------------------------------" << endl;
    cout << "---------- ENTER STUDENT'S WEIGHT ----------" << endl;
    cout << "--------------------------------------------" << endl;
    cout << endl;

    std::vector<float> weights(number_of_students);

    for(int i=0; i<number_of_students; ++i) {
      cin >> weights[i];
    }

    cout << "Average is: " << std::accumulate(weights.begin(), weights.end(), 0.f)
                                      / number_of_students
      << std::endl;

    return EXIT_SUCCESS;
}
于 2012-11-04T23:54:38.053 に答える
6

サイクルで1つの変数を使用できます。例:

for (int i = 0; i < number_of_students; i++) {
    int weight;
    cin >> weight;
    if (weight < 65)
        result++;
}
于 2012-11-04T23:55:54.163 に答える
1

new演算子を使用して、整数の配列を作成します。

cin >> number_of_students;
int* x = new int[number_of_students];

これで、の配列ができsize=number_of_studentsました。ウェイトを保存するために使用します。


編集この方法で対処することは、実際には最善ではありません(メモリリークなどに対処する)。特にコメントやその他の回答に注意してください。中間ストレージを使用しないものとstd::vectorベースのソリューション。

于 2012-11-04T23:54:34.420 に答える
1

質問がないかもしれませんが、次のような特定の長さの配列を作成できます

int* a = new int[number_of_students];

for (int i = 0; i < number_of_students; i++) {
    cin >> a[i];
}

それがお役に立てば幸いです...

于 2012-11-04T23:58:00.143 に答える