当前位置:   article > 正文

【C++之对象数组和对象指针2】找到成绩最高的学生_最高分数top c++

最高分数top c++

题目要求

建立一个对象数组,内放5个学生的数据(学号、成绩),设立一个函数 max ,用指向对象的指针作函数参数,在 max 函数中找到5个学生中的成绩最高者,并输出其学号。

——谭浩强的《C++面向对象程序设计》第3章习题第5小题

程序

student.h

/*
*************************************************************************
@file:    student.h
@date:   2020.11.7
@author: Xiaoxiao
@blog:    https://blog.csdn.net/weixin_43470383/article/details/109541159
*************************************************************************
*/

#include <iostream>
using namespace std;

class Student // 声明类类型
{
private: // 声明私有部分
	int num;		 // 学号
	int score;       // 成绩

public: // 声明公用部分
	Student(int n, int s) : num(n), score(s) {}; // 定义带参数的构造函数,并用参数的初始化表对数据成员初始化
	void max(Student *);                         // 找到成绩最高的学生,并输出其学号
};
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22

student.cpp

/*
*************************************************************************
@file:    student.cpp
@date:   2020.11.7
@author: Xiaoxiao
@blog:    https://blog.csdn.net/weixin_43470383/article/details/109541159
*************************************************************************
*/

#include"student.h"

// 类外定义成员函数
void Student::max(Student *arr)   // 找到成绩最高的学生,并输出其学号
{
	int max_score = arr[0].score; // 记下最高成绩
	int max_num = 0;              // 记下成绩最高的学生的学号
	for (int i = 0; i < 5; i++)
	{
		if (arr[i].score > max_score)
		{
			max_score = arr[i].score;
			max_num = i;
		}
	}
	cout << "The number of student who get the highest score:"<< endl << arr[max_num].num << endl;
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26

main.cpp

/*
*************************************************************************
@file:    main.cpp
@date:   2020.11.7
@author: Xiaoxiao
@blog:    https://blog.csdn.net/weixin_43470383/article/details/109541159
*************************************************************************
*/

#include "student.h"

int main()
{
	Student stu[5] = {
		Student(1, 96),
		Student(2, 97),
		Student(4, 99),
		Student(8, 100),
		Student(16, 98)
	}; // 定义对象数组
	
	Student *p;    // 定义p为指向Student类对象的指针变量
	p = stu;       // 将stu的起始地址赋给p
	// 或:Student *p = stu;

	stu[5].max(p); // 调用对象stu[5]的公有成员函数max
	
	system("pause");
	return 0;
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30

运行结果

运行结果
实现了输出最高成绩的学生的学号。

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/Monodyee/article/detail/396421
推荐阅读
相关标签
  

闽ICP备14008679号