前言: 这个题并不难 起初不打算针对这个题水个文章了 但是有几个值得注意的点 且这个题也是我第一次正式用c++类的结构写题 所以还是水一篇吧
题目:
先看一下最终的版本 :
#include<iostream>
using namespace std;
class Student
{
public:
void get_information();
void show_information();
int get_score();
private:
char name[11];
char num[11];
int score;
};
int Student::get_score()
{
return score;
}
void Student::get_information()
{
cin >> name >> num >> score;
}
void Student::show_information()
{
cout << name << " " << num << endl;
}
int main()
{
int n = 0;
cin >> n;
Student* arr = new Student[n];
for (int i = 0; i < n; i++)
{
arr[i].get_information();
}
int max = 0;
int min = 0;
for (int i = 0; i < n; i++)
{
if (arr[max].get_score() < arr[i].get_score())
max = i;
if (arr[i].get_score() < arr[min].get_score())
min = i;
}
arr[max].show_information();
arr[min].show_information();
return 0;
}
其实这个题并不难理解 就不解释了
然后给个我最初的错误版本:
#include<iostream>
using namespace std;
class Student
{
public:
void get_information();
void show_information();
int get_score();
private:
char name[10];
char num[10];
int score;
};
int Student::get_score()
{
return score;
}
void Student::get_information()
{
cin >> name >> num >> score;
}
void Student::show_information()
{
cout << name << " " << num << endl;
}
int main()
{
int n = 0;
cin >> n;
Student arr[100];
for (int i = 0; i < n; i++)
{
arr[i].get_information();
}
int max = 0;
int min = 0;
for (int i = 0; i < n; i++)
{
if (arr[max].get_score() < arr[i].get_score())
max = i;
if (arr[i].get_score() < arr[min].get_score())
min = i;
}
arr[max].show_information();
arr[min].show_information();
return 0;
}
这个最开始提交上去之后是错误的 开始的时候不太明白 现在知道了 说一下:
1. 题目中要求 学生的姓名学号 为不超过10个字符的字符串 其实大可以直接定义为string类型 但是我没有(经测试 string类型是完全可以的 ) 接着说: 不超过10字符的字符串 我定义成了10个字符大小的数组 这就不对了 因为如果输入10个字符的话 就没有空间存放'\0'了 也就导致输出姓名时会出错 所以应定义为11个字符大小的字符串 或者直接定义为string也可以
2. 这个题要求 输入多少学生的信息由最开始输入的整数决定 但是我直接定义成了100 大小的人的数组 经过提交发现错误 后来改成1000 就成功了 也就是某个测试点中输入了大于100的人的信息 用100大小的数组存放当然不对了 但是由于当时我还没学过new 也就是动态开辟存储空间 后来去网上查了一下 学习一下大致的定义规则 就有了成功版本中 动态开辟数组空间
----------------------------------------------------
如果想换别的办法 也是完全可以的 其实不用定义类 嗯...... 比如 你可以创建结构体 且也可以不用创建数组 用临时的变量直接比大小即可
新发现:结构体变量竟然可以直接赋值. 之前不知道
#include<iostream>
using namespace std;
typedef struct Student
{
char name[100];
char number[100];
int score;
}student;
student _max={"","",0},_min={"","",100};
int main()
{
int cnt;
cin>>cnt;
while(cnt--)
{
student use;
cin>>use.name;
cin>>use.number;
cin>>use.score;
if(use.score>_max.score)
_max=use;
if(use.score<_min.score)
_min=use;
}
cout<<_max.name<<" "<<_max.number<<endl;
cout<<_min.name<<" "<<_min.number;
return 0;
}