6、小作业:
用一个函数来实现一个功能,分别统计全市在校学生的平均年龄。学生包括小学生、中学生、高中生、大学生 等。用一个函数来实现!
下节课会给大家解答这个小作业,用的方法也是下节课即将要讲解的,大家先事先自己试试吧!
#include <iostream> using namespace std; enum Estudent { Student = 0, Pupil, Middle, High }; class C_Student { public: Estudent type = Student; int age; }; class C_Pupil:public C_Student { public: int arithmetic; C_Pupil() { type = Pupil; } }; class C_Middle:public C_Pupil { public: int grammar; C_Middle() { type = Middle; } }; class C_High :public C_Middle { public: int geography; C_High() { type = High; } }; int test(C_Student* stu,int x) { if(!stu || x <= 0) { return 0; } Estudent stu_type = stu[0].type; int sum = 0; for (int idx = 0; idx < x; idx++) { switch (stu_type) { case Pupil: sum += ((C_Pupil*)stu)[idx].age; break; case Middle: sum += ((C_Middle*)stu)[idx].age; break; case High: sum += ((C_High*)stu)[idx].age; break; default: break; } } int average_age = sum / x; switch (stu_type) { case Pupil: cout << "Pupil平均年龄 = " << average_age << endl; break; case Middle: cout << "Middle平均年龄 = " << average_age << endl; break; case High: cout << "High平均年龄 = " << average_age << endl; break; default: break; } return average_age; } int main() { C_High a[4]; a[0].age = 10; a[1].age = 111; a[2].age = 13; a[3].age = 18; test(a, 4); return 0; }