用c++编写一个程序,要求创建一个类,输入若干个学生的数据,包括学号,姓名和三门课程的成绩;
参考代码:
#include <iostream>
#include <string>
using namespace std;
#define MAX 100
class Student
{
private:
string num;
string name;
double subject[3];
double total;
public:
void input(Student s[], int);
void sort(Student s[], int);
void print(Student s[], int);
}stu[MAX];
void Student::input(Student s[], int n)
{
for (int i = 0; i < n; i++)
{
cout << "输入第" << i + 1 << "个学生的学号:";
cin >> s[i].num;
cout << "输入第" << i + 1 << "个学生的姓名:";
cin >> s[i].name;
s[i].total = 0;
for (int j = 0; j < 3; j++)
{
cout << "输入第" << j + 1 << "门课的成绩:";
cin >> s[i].subject[j];
s[i].total += s[i].subject[j];
}
cout << endl;
}
}
void Student::sort(Student s[], int n)
{
for (int i = 0; i < n-1; i++)
{
for (int j = i + 1; j < n; j++)
{
if (s[i].total < s[j].total)
{
Student tmp = s[i];
s[i] = s[j];
s[j] = tmp;
}
}
}
}
void Student::print(Student s[], int n)
{
for (int i = 0; i < n; i++)
{
cout << "第" << i + 1 << "名" << endl;
cout << "学号:" << s[i].num << endl;
cout << "姓名:" << s[i].name << endl;
for (int j = 0; j < 3; j++)
{
cout << "第" << j + 1 << "门课的成绩:" << s[i].subject[j] << endl;
}
cout << endl;
}
}
int main()
{
int num;
cout << "输入学生个数:";
cin >> num;
cout << endl;
Student s;
s.input(stu, num);
s.sort(stu, num);
s.print(stu, num);
return 0;
}
1、#include <iostream>#include <string>using namespace std;#define
2、MAX 100class Student{private:string num;string name;double subject[3];
3、double total;public:void input(Student s[], int);void sort(Student s[], int);
void print(Student s[], int);}stu[MAX];void Student::input(Student s[], int n)
{for (int i = 0; i < n; i++){cout << "输入第" << i + 1 << "个学生的学号:";
4、cin >> s[i].num;cout << "输入第" << i + 1 << "个学生的姓名:";cin >> s[i].name;
s[i].total = 0;for (int j = 0; j < 3; j++){cout << "输入第" << j + 1 << "门课的成绩:";
cin >> s[i].subject[j];s[i].total += s[i].subject[j];}cout << endl;}
void Student::sort(Student s[], int n){for (int i = 0; i < n-1; i++){for (int j = i + 1; j < n; j++){if (s[i].total < s[j].total){Student tmp = s[i];
5、s[i] = s[j];s[j] = tmp;}void Student::print(Student s[], int n)
{for (int i = 0; i < n; i++){cout << "第" << i + 1 << "名" << endl;cout << "学号:" << s[i].num << endl;cout << "姓名:" << s[i].name << endl;for (int j = 0; j < 3; j++){cout << "第" << j + 1 << "门课的成绩:" << s[i].subject[j] << endl;}cout << endl;}
int main(){int num;cout << "输入学生个数:";cin >> num;cout << endl;
Student s;s.input(stu, num);s.sort(stu, num);s.print(stu, num);return 0;}