【任務4】設計一個學生類,包括學號(num)和成績(score)。建立一個對象數組,內放5個學生的數據,要求:
(1) 用指針指向數組首元素,輸出第1、3、5個學生的信息;
(2) 設計一個函數max,用指向對象的指針作函數參數,在max函數中找出5個學生中成績最高者,並輸出其學號。
* 程序的版權和版本聲明部分
* Copyright (c) 2011, 煙臺大學計算機學院學生
* All rights reserved.
* 文件名稱: 長方柱類
* 作 者:郭廣建
* 完成日期: 2012年 3月 20日
* 版 本 號: 1.0
源程序:
#include <iostream>
using namespace std;
class Student
{
public:
Student(int n, float s):num(n),score(s){};
int get_num(){return num;} //這個方法很好借鑑老師的
float get_score(){return score;}
void output();
private:
int num ;
float score;
};
int max(Student *Stu)
{
float max_score = Stu[0].get_score();
int i, j;
for(i = 1; i < 5; ++i)
{
if(Stu[i].get_score() > max_score)
{
max_score = Stu[i].get_score();
j = i;
}
}
return Stu[j].get_num();
}
void Student::output()
{
cout << "學號是:" << num << "成績是:" << score <<endl;
}
int main()
{
Student Stu[5] = {Student(1001,87),Student(1002,91),Student(1003,90.5),Student(1004,88.5),Student(1005,97.5)};
for(int i = 0; i < 5; i+=2)
{
cout << "第" <<i + 1 << "個學生的信息是:";
Stu[i].output();
}
cout << "學生中成績最高的同學的學號是:" << max(Stu) <<endl;
return 0;
}
運行結果: