/*
* Copyright (c) 2014, 烟台大学计算机学院
* All rights reserved.
* 文件名称:test.cpp
* 作 者:刘佳琦
* 完成日期:2015年 3 月 30 日
* 版 本 号:v1.0
*
* 问题描述:设计一个学生类Student,数据成员包括学号(num)和成绩(score),成员函数根据需要自行设计(建议配备需要的set、get函数,以及必要的输入或输出,给出的代码中也可以找到需要成员函数的线索)。在main函数中,要做到:
建立一个对象数组,通过初始化,设置5个学生的数据,要求:
用指针指向数组首元素,输出第1、3、5个学生的信息;
设
* 程序输出:无
*/
#include <iostream>
#include <cmath>
using namespace std;
class Student
{
public:
Student(int n,double s)
{
num=n;
score=s;
}
int getNum()
{
return num;
}
double getScore()
{
return score;
}
void output()
{
cout<<num<<" "<<score<<endl;
}
private:
int num; //学号
double score; //成绩
};
int max(Student *arr);
int main()
{
Student *p;//定义一个指针
Student stud[5]=
{
Student(101,78.5),Student(102,85.5),Student(103,100),
Student(104,98.5),Student(105,100)
};
p=stud;//指针用来指向数组里的值
for(int i=0; i<5; i+=2,p+=2)
{
cout<<"学生"<<i+1<<": ";
p->output(); //调用函数,指针P指向数组里的值赋给调用函数。
}
//找出个学生中成绩最高者,并输出其学号
double maxs = max(stud); //调用函数求最高成绩
cout<<"5个学生中成绩最高者的学号为: ";
for(int i=0; i<5; i++)
{
if(abs(stud[i].getScore() - maxs)<1e-7) //浮点数不能直接比较相等,只要相减小于一个很小的值,就认为相等
cout<<stud[i].getNum()<<" ";
}
cout<<endl;
return 0;
}
//定义函数max,返回arr指向的对象数组中的最高成绩者的学号
int max(Student *arr)
{
double maxs=arr[0].getScore();
for(int i=1; i<5; i++)
if(arr[i].getScore()>maxs)
{
maxs=arr[i].getScore();
}
return maxs;
}
运行结果:
学习心得:上课听了老师的一种使用指针的办法,就立刻来上机试验了一下,几种用法试验了一下,把老师说的最正规的使用指针的办法发成了这篇博文,上课通过老师的讲解慢慢回顾起了指针的知识,虽然现在还不没有立刻感受到指针的好处,但是敢于用了,也慢慢开始接触,对于指针的基本用法都有所了解,就是有时候在指针的范围上会犯迷糊,取地址和指向也有时候会犯迷糊,在下节课之前还是好好看看以前的博文,回顾好知识点。