谭浩强C++课后习题32——对象数组

谭浩强C++课后习题32——对象数组

题目描述:建立一个对象数组,内放5个学生的数据(学号,成绩),设立一个函数max,在max函数中找出5个学生中成绩最高者,并输出其学号。

#include<iostream>
using namespace std;
class student {
private:
	int id;
	double score;
public:
	student(int i, double s) :id(i), score(s) {}
	double getScore() { return score; }
	void show() { cout << "学号:" << id << endl << "成绩:" << score << endl; }
};
int max(student stu[], int n) {
	int maxi = 0;
	for (int i = 0;i < n;i++) {
		if (stu[i].getScore() > stu[maxi].getScore())
			maxi = i;
	}
	return maxi;
}
int main() {
	student stu[5] = {
		student(101,78.5),student(102,80),student(103,65.5),student(104,86.5),student(105,76.5)
	};
	int maxi = max(stu, 5);
	cout << "成绩最好的学生:" << endl;
	stu[maxi].show();
	return 0;
}

运行测试结果:
在这里插入图片描述

发布了35 篇原创文章 · 获赞 35 · 访问量 567

猜你喜欢

转载自blog.csdn.net/weixin_45295612/article/details/105310463