gpt4 book ai didi

c++ - 如何在结构数组中显示学生姓名以及 GPA 高于平均水平的 ID

转载 作者:太空宇宙 更新时间:2023-11-04 12:33:00 25 4
gpt4 key购买 nike

我的任务是显示 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:John,GPA 3.5

学生 2:Bob,GPA 4.0

学生 3:Mike,GPA 2.3

平均 GPA:3.23

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

最佳答案

我建议您考虑 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

关于c++ - 如何在结构数组中显示学生姓名以及 GPA 高于平均水平的 ID,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57898344/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com