kolioi

55. Total Average of Students C++

Jan 5th, 2019
213
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.14 KB | None | 0 0
  1. #include <iostream>
  2. #include <string>
  3. #include <vector>
  4.  
  5. using namespace std;
  6.  
  7. class Student
  8. {
  9. public:
  10.     Student(string fname, string lname, double gpa) :
  11.         first_name(fname), last_name(lname), GPA(gpa)
  12.     {}
  13.  
  14.     void print() const
  15.     {
  16.         cout << first_name << ' ' << last_name << ' ' << GPA << endl;
  17.     }
  18.  
  19.     double get_gpa() const
  20.     {
  21.         return GPA;
  22.     }
  23.  
  24. private:
  25.     string first_name;
  26.     string last_name;
  27.     double GPA;
  28. };
  29.  
  30. vector<Student> read_student_info(size_t n)
  31. {
  32.     vector<Student> students;
  33.     for (size_t i = 0; i < n; ++i)
  34.     {
  35.         string fname, lname;
  36.         double gpa;
  37.         cin >> fname >> lname >> gpa;
  38.         Student student(fname, lname, gpa);
  39.         students.push_back(student);
  40.     }
  41.  
  42.     return students;
  43. }
  44.  
  45. double calc_total_gpa(const vector<Student>& students)
  46. {
  47.     if (students.empty())
  48.         return 0;
  49.  
  50.     double sum = 0;
  51.     for (auto& student : students)
  52.         sum += student.get_gpa();
  53.  
  54.     return sum / students.size();
  55. }
  56.  
  57. int main()
  58. {
  59.     size_t n;
  60.     cin >> n;
  61.  
  62.     vector<Student> students = read_student_info(n);
  63.  
  64.     for (auto& student : students)
  65.         student.print();
  66.  
  67.     cout << static_cast<int>(calc_total_gpa(students)) << endl;
  68.  
  69.     return 0;
  70. }
Advertisement
Add Comment
Please, Sign In to add comment