注册 登录
编程论坛 C++教室

通过指针指向对象,传到max() 后,比较对象中分数,输出最大分数,及相应的号数?

鸿鹄 发布于 2010-04-19 23:49, 516 次点击
我这样写的,但觉得好复杂啊,而且还出现很多错误,请问怎么修改?

#include <iostream>
using namespace std;
class Studentdent
{
public:
   
    Studentdent(int n, float s):num(n),score(s){};
private:
    int num;
    int score ;
};
void max( Student *a1,Student *a2,Student *a3,Student*a4, Student *a5)
{ int max;
 max=(*a1).score>(*a2).score? (*a1).score:((*a2).score>(*a3).score? (*a2).score:((*a3).score>(*a4).score ?(*a3).score :((*a4).score>(*a5).score ?(*a4).score:(*a5).score)));
   int nb;   
   return max;
   if ((*a1).score==max) nb=a1->num;
    else if ((*a2).score==max) nb=a2->num;
    else if((*a3).score==max)  nb= a3->num;
    else if((*a4).score==max) nb= a4->num;
    else  nb=a5->num;

    cout<<"最高分是"<<max<<endl;
    cout<<"该同学的学号是"<<nb;

   
}

void main()
{   
    Studentdent stu[5]={
        Student(1,80),
        Student(2,89),
        Student(3,78),
        Student(4,99),
        Student(5,68)
    };

    Studentdent *p1,*p2,*p3,*p4,*p5;
    p1=&stu[0];
    p2=&stu[1];
    p3=&stu[2];
    p4=&stu[3];
    p5=&stu[4];
   void max(p1,p2,p3,p4,p5);

}
3 回复
#2
debroa7232010-04-20 00:35
class Student
{
public:
    Student(int n, float s):num(n),score(s){};
    void Show(void);
    int num;
    int score ;
};

void Student::Show(void)
{
    cout<<"同学(学号:"<<num<<")的分数是"<<score<<endl;
}
Student * max( Student *a1,Student *a2)
{
   if ( a1->score > a2->score)
        return a1;
   return a2;
}
void main()
{   
    Student stu[5]={
        Student(1,80),
        Student(2,89),
        Student(3,78),
        Student(4,99),
        Student(5,68)
    };

    Student* MaxStudent = stu[0];
    for(int i = 1 ; i < 5 ; ++i)
    {
        MaxStudent = Max(MaxStudent,&stu[i]);
     }
    cout<<"分数最高的是:"<<endl;
    MaxStudent->Show();

}
办法有很多,这个给你参考。
#3
flyingzc2010-04-20 13:26
回复 2楼 debroa723
你的代码有错误啊,编译不通过
#4
debroa7232010-04-20 21:33
class Student
{
public:
    Student(int n, float s):num(n),score(s){};
    void Show(void);
    int num;
    int score ;
};

void Student::Show(void)
{
    cout<<"同学(学号:"<<num<<")的分数是"<<score<<endl;
}

Student* Max( Student* a1,Student* a2)
{
    if ( a1->score > a2->score)
        return a1;
    return a2;
}
void main()
{   
    Student stu[5]={
        Student(1,80),
        Student(2,89),
        Student(3,78),
        Student(4,99),
        Student(5,68)
    };

    Student* MaxStudent = &(stu[0]);
    for(int i = 1 ; i < 5 ; ++i)
    {
        MaxStudent = Max(MaxStudent,&stu[i]);
    }
    cout<<"分数最高的是:"<<endl;
    MaxStudent->Show();
}
没检查,有几处笔误,改过来了。

1