【问题标题】:How to display student names along with ID with above average GPA in a structure array如何在结构数组中显示具有高于平均 GPA 的学生姓名和 ID
【发布时间】:2019-09-12 00:42:52
【问题描述】:

我的任务是显示 GPA 高于平均水平的学生的姓名、ID、GPA。

#include <iostream>
#include <string>

using namespace std;

struct student{

    string name;
    char stdid[20];
    int age;
    char gender;
    float gpa;

};


int main() {

    int amount;
    float sum=0.0, average;

    struct student std[40];

    struct student *ptr = NULL;

    ptr = std;

    cout<<"enter the amount of students you want to input"<<endl;
    cin>>amount;


    for (int i=0;i<amount;i++)
    {
        cout<<"please enter details such as name, ID, age, gender and GPA for student "<< (i+1)<<endl;
        cout<<"Student ID : "<<endl;
        cin>>ptr->stdid;
        cout<<"Name : "<<endl;
        cin>>ptr->name;
        cout<<"Age : "<<endl;
        cin>>ptr->age;
        cout<<"Gender : "<<endl;
        cin>>ptr->gender;
        cout<<"GPA : "<<endl;
        cin>>ptr->gpa;
        sum += ptr->gpa;
    }

    average = sum/amount;
    cout << "Average GPA = " << average;


return 0;
}

例如,如果用户在程序中输入 3 个学生,例如:

学生 1:约翰,GPA 3.5

学生 2:鲍勃,GPA 4.0

学生 3:迈克,2.3 GPA

平均 GPA:3.23

然后输出将显示所有 GPA 高于 3.23 的学生的姓名、ID 和 GPA

【问题讨论】:

  • 您永远不会增加ptr 以指向std 中的以下学生。使用std 作为变量名也是一个坏主意:可能与namespace std 冲突
  • I was surprised to find gcc doesn't complain about a namespace std mixed with a variable std。我稍后会查原因。但即使编译器不会与名为 std 的标识符混淆,人类也可能会。
  • 好的!我现在已将 std 变量更改为 stdnt
  • 欢迎来到 Stack Overflow。在你继续这个项目之前,你必须学会​​遍历一个数组。

标签: c++ arrays data-structures struct


【解决方案1】:

我建议您考虑使用 std::vector 容器来存储 student 对象和算法 std::accumulate() 来计算平均值:

std::vector<student> students;

// ...
// fill the vector of students
// ...

// calculate the sum of all GPAs
float sum = std::accumulate(students.begin(), students.end(), 0.0f,
                            [](float acc, const student& elem) {
                               return acc + elem.gpa;       
                            }
);

// calculate the average GPA
auto avg = sum / students.size();

为了显示student 对象,您可以定义以下输出流运算符

std::ostream& operator<<(std::ostream& os, student const& s) {
   os << s.stdid << " " << s.gpa << '\n';
}

然后,您可以遍历 student 对象的整个集合并仅显示 GPA 高于平均水平的对象:

for (auto const& student: students)
   if (student.gpa > avg)
      std::cout << student; // call the output stream operator defined above

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-03-01
    • 2018-04-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多