林惜城


私信TA

用户名:reminder

访问量:27417

签 名:

等  级
排  名 94
经  验 8463
参赛次数 0
文章发表 95
年  龄 0
在职情况 学生
学  校 西安电子科技大学
专  业

  自我简介:

哈姆

TA的其他文章


解题思路:

上题传送门:https://blog.dotcpp.com/a/84942

上一题还没想好怎么用class代替struct,这一题机会就来了。构造方法和上题完全一致,都是定义包含N个对象的数组。(上一题是包含N个结构体成员的数组)

而且不管写不写input()函数,student类的构造函数都是要写的,干脆就不写了,用for循环输入,每轮输入都把参数传给一个student对象。

其他也没什么在逻辑上有难度的,主要问题是如何写的简洁美观,目前版本我不太满意。


注意事项:

输出平均分应该有更好的写法,我目前的写法是建一个大小为3的数组,每输入一个分数就加到对应的数组成员中,最后除以N输出,感觉写的很丑陋。


参考代码:

#include <iostream>
#include <cstring>

using namespace std;

class student {
	public:
		// 构造学生对象
		void setInfo(char *id, char *name, short *score) {
			strcpy(this->id, id);
			strcpy(this->name, name);
			for(int i = 0; i < 3; i++) {
				this->score[i] = score[i];
			}
		}
		// 打印学生信息
		void printInfo() {
			cout << id << " " << name << " " << score[0] << " " << score[1] << " " << score[2] << endl;
		}
		// 总分,用于比较
		short sumScore() {
			return score[0] + score[1] + score[2];
		}
	private:
		char id[10]; // 学号
		char name[10]; // 姓名
		short score[3]; // 成绩
};

int main() {
	short N = 0; // 学生数
	cin >> N;
	
	student stu[N]; // 构造N个学生对象
	short avgScore[3] = { 0 }; // 平均分,分为3门课
	short maxScore = 0; // 最高分
	short maxScoreIndex = 0; // 存储总分最高的学生在数组中的位置
	
	// 输入学生信息
	for(int i = 0; i < N; i++) {
		char id[10];
		char name[10];
		short score[3] = { 0 };
		cin >> id >> name;
		for(int j = 0; j < 3; j++) {
			cin >> score[j];
			avgScore[j] += score[j]; // 每输入一门课的分数就加到对应课程的avgScore上
		}
		stu[i].setInfo(id, name, score); // 存储学生信息,用于打印
	}
	
	for(int i = 0; i < N; i++) {
		if(stu[i].sumScore() > maxScore) {
			maxScore = stu[i].sumScore(); // 更新最高分
			maxScoreIndex = i; // 更新最高分的学生位置
		}
	}
	
	cout << avgScore[0] / N << " " << avgScore[1] / N << " " << avgScore[2] / N << endl; // 打印平均分
	stu[maxScoreIndex].printInfo(); // 打印最高分学生
	return 0;
}


 

0.0分

2 人评分

看不懂代码?想转换其他语言的代码? 或者想问其他问题? 试试问问AI编程助手,随时响应你的问题:

编程语言转换万能编程问答  

代码解释器

代码纠错

SQL生成与解释

  评论区