3

我正在为学校做一个项目。情况是这样的:

您应该能够为n名学生输入权重。计算学生的平均体重并输出有多少学生的体重低于 65 公斤。

到目前为止,我有这个 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 个新的权重变量。

编辑:

我可以计算平均体重,找出有多少学生的体重低于 65 公斤。只有我坚持定义将添加多少学生的变量数量。计算学生的平均体重并输出有多少学生的体重低于 65 公斤。

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

您可以在循环中使用一个变量。例子:

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 回答