【问题描述】
编写一个能管理多条学生信息的程序。
设计 Student 类并实现用于管理学生信息表(学生表的长度不超过5)的3个函数,成员变量和函数的访问性都为公有的,具体类结构和函数要求如下:
学号,int类型
姓名,string类型
分数,float类型
带参构造函数:Student(int sid,string name,float sco),分别用这三个参数设置内部的三个成员。
void Add(int sid,string name,float sco),函数用于向学生表的末尾添加一条学生记录。
void PrintAll(),输出学生表中所有的记录,格式为:学号 姓名 成绩。
void Average(),计算学生表中学生的平均成绩并输出,格式为:平均成绩 计算结果。
提示:学生表可以用全局对象数组来完成。
【样例输入】
0 厉宏富 96
1 冷欣荣 85
2 鲍俊民 76
说明,以 ctrl+z 结束输入
【样例输出】
0 厉宏富 96
1 冷欣荣 85
2 鲍俊民 76
平均成绩 85.6667
#include <string>
#include <iostream>
using namespace std;
/********* Begin *********/
class Student
{
//在此处声明所需的成员
public:
int SID;
string Name;
float Score;
int listCount;
Student(int sid,string name,float sco);
Student(): listCount(0){};
void Add(int sid,string name,float sco);
void PrintAll();
void Average();
};
Student list[50]; // 全局对象数组模拟的学生表
int listCount; // 学生表中的记录的条数
//定义成员函数
Student::Student(int sid,string name,float sco)
{
SID=sid;
Name=name;
Score=sco;
}
/********* End *********/
void Add(int sid,string name,float sco)
{
/********* Begin *********/
//向学生表中添加一条记录
list[listCount++]=Student(sid,name,sco);
/********* End *********/
}
void PrintAll()
{
/********* Begin *********/
//打印出学生表中所有记录
int i=0;
for(i=0;i<listCount;i++)
{
cout<<list[i].SID<<" "<<list[i].Name<<" "<<list[i].Score<<endl;
}
/********* End *********/
}
void Average()
{
/********* Begin *********/
//计算并打印出学生表中的平均成绩
float totalScore = 0;
for (int i = 0; i < listCount; i++)
{
totalScore += list[i].Score;
}
cout << "平均成绩 " << totalScore / listCount << endl;
/********* End *********/
}
int main()
{
int sid;
string name;
float score;
cin>>sid>>name>>score;
while(!cin.eof())
{
Add(sid,name,score);
cin>>sid>>name>>score;
}
PrintAll();
Average();
return 0;
}
【注】此分栏为西安理工大学C++练习题,所有答案仅供同学们参考。