【东华大学oj】10 寻找最好成绩(面向对象)

10 寻找最好成绩

作者: 冯向阳时间限制: 1S章节: 类与对象

问题描述 :

建立一个对象数组,内放若干个学生的学习数据(学号,成绩)。

设计一函数max,使用学生对象数组作为参数,在max函数里找出这些学生中成绩最高者,并输出其学号及成绩。

在main函数中使用并测试之。在main函数中读入学生数据,创建学生对象数组,并调用max函数输出成绩最高者。

如果有多名学生成绩最高,则按照输入的先后顺序输出这些学生的信息。

要求:

(1)学生类的名称为Student,定义如下:

     Student{

        private:

          int num;  //学号

          float score; //分数

        public:  //成员函数仅给出原型,需自行设计

           Student(int num);

           void SetScore(float);

           int GetNum();

           float GetScore();

      };

对于Student类,可自行增加属性和成员函数。

(2)max函数原型为void max( Student arr[] ,int n); //函数体需自行设计

main函数可参考如下实现:

int main( )

{

   int i, n, num;

   float score;

   cin>>n;

   Student stu[n];

   for( i = 0; i < n; i++)

   {

        cin>>num>>score;

        stu[i] = Student(num);

        stu[i].SetScore(score);

    }

    max(stu, n );

    return 0;

}

输入说明 :

输入的第一行为学生的数目n,其后n行为n个学生的数据,每个学生的数据占一行(学号,成绩)

学号与成绩之间以空格分隔,每行的开头和结尾无多余的空格。

输出说明 :

输出成绩最高者的学号和成绩,其间以一个空格分隔。

如果输出多名学生,则每名学生独占一行。

输出无多余空行及多余空格。

#include <iostream>
#include <cstring>
#include <vector>
using namespace std;

class Student
{
private:

    int num;  //学号

    float score; //分数

public:  //成员函数仅给出原型,需自行设计

    Student(int num) :num(num) {}
    Student() {}

    void SetScore(float s)
    {
        score=s;
    }

    int GetNum()
    {
        return num;
    }

    float GetScore()
    {
        return score;
    }

};

//(2)max函数原型为
void max( Student arr[],int n)
{
    double maxScore=arr[0].GetScore();
    int i;
    for(i=1; i<n; i++)
    {
        if(arr[i].GetScore()>maxScore)
            maxScore=arr[i].GetScore();
    }

    vector<pair<int, float>> maxStudents; // 保存分数最高的学生的学号和分数
    for (int i = 0; i < n; i++)
    {
        if (arr[i].GetScore() == maxScore)
        {
            maxStudents.push_back(make_pair(arr[i].GetNum(), arr[i].GetScore()));
        }
    }

    for (int i = 0; i < maxStudents.size(); i++)
    {
        cout << maxStudents[i].first << " " << maxStudents[i].second << endl;
    }
}

int main( )
{

    int i, n, num;

    float score;

    cin>>n;

    Student stu[n];

    for( i = 0; i < n; i++)

    {

        cin>>num>>score;

        stu[i] = Student(num);

        stu[i].SetScore(score);

    }

    max(stu, n );

    return 0;

}

  • 6
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

ixll625

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值