设计一个学生类,其中数据成员有学号、姓名、年龄、3门课程的成绩,以及若干成员函数。并利用这个类建立一个对象数组。(1)求第一门课的平均成绩;(2)找出有两门以上课程不及格的学生,输出他们的学号和全部课程成绩和平均成绩;(3)找出平均成绩在90分以上或全部课程成绩在85分以上的学生。分别编3个函数实现以上三个要求。 要求: (1)使用构造函数实现对数据的输入。 (2)以上三个要求必须用成员函数实现。 (3)在头文件中完成类的声明,在.cpp中完成类的实现,在主文件(.cpp)中完成主函数编写。参见教材8.5.2以及P262,第8章第4题。
时间: 2024-03-24 08:37:17 浏览: 93
以下是实现该问题的代码:
头文件 student.h:
```c++
#ifndef STUDENT_H
#define STUDENT_H
#include <string>
using namespace std;
class Student {
public:
Student(string id, string name, int age, float score1, float score2, float score3);
float avgScore1();
void printFailed();
void printExcellent();
private:
string id;
string name;
int age;
float score1;
float score2;
float score3;
};
#endif
```
实现文件 student.cpp:
```c++
#include <iostream>
#include "student.h"
using namespace std;
Student::Student(string id, string name, int age, float score1, float score2, float score3) {
this->id = id;
this->name = name;
this->age = age;
this->score1 = score1;
this->score2 = score2;
this->score3 = score3;
}
float Student::avgScore1() {
return (score1 + score2 + score3) / 3;
}
void Student::printFailed() {
if (score1 < 60 || score2 < 60 || score3 < 60) {
cout << "学号:" << id << endl;
cout << "姓名:" << name << endl;
cout << "年龄:" << age << endl;
cout << "成绩1:" << score1 << endl;
cout << "成绩2:" << score2 << endl;
cout << "成绩3:" << score3 << endl;
cout << "平均成绩:" << avgScore1() << endl;
cout << endl;
}
}
void Student::printExcellent() {
if (avgScore1() >= 90 || score1 >= 85 && score2 >= 85 && score3 >= 85) {
cout << "学号:" << id << endl;
cout << "姓名:" << name << endl;
cout << "年龄:" << age << endl;
cout << "成绩1:" << score1 << endl;
cout << "成绩2:" << score2 << endl;
cout << "成绩3:" << score3 << endl;
cout << "平均成绩:" << avgScore1() << endl;
cout << endl;
}
}
```
主文件 main.cpp:
```c++
#include <iostream>
#include "student.h"
using namespace std;
int main() {
Student students[] = {
Student("001", "张三", 20, 80, 70, 90),
Student("002", "李四", 21, 70, 50, 40),
Student("003", "王五", 19, 90, 95, 80),
Student("004", "赵六", 22, 85, 80, 95),
Student("005", "钱七", 20, 95, 85, 90),
};
// 求第一门课的平均成绩
float sum = 0;
for (int i = 0; i < 5; i++) {
sum += students[i].avgScore1();
}
cout << "第一门课的平均成绩为:" << sum / 5 << endl << endl;
// 找出有两门以上课程不及格的学生
cout << "有两门以上课程不及格的学生:" << endl;
for (int i = 0; i < 5; i++) {
students[i].printFailed();
}
// 找出平均成绩在90分以上或全部课程成绩在85分以上的学生
cout << "平均成绩在90分以上或全部课程成绩在85分以上的学生:" << endl;
for (int i = 0; i < 5; i++) {
students[i].printExcellent();
}
return 0;
}
```
阅读全文
相关推荐

















