1. 程式人生 > >函數指針(理科實驗班)

函數指針(理科實驗班)

優秀 logs ace 入學 als 正整數 接下來 需要 答案

夢山高中現需要將某普通班的最優秀學生調整入理科實驗班。為此,將從兩個方面考察學生,一是數學和英語兩門課的總分;另一個是所有四門課的總分。分別找出兩科總分和全科總分的第一名,並從中決定調整人選。

輸入將首先輸入學生數n, (n為不超過80的正整數);接下來依次輸入各位學生的學號,數學、英語、語文、理科綜合成績。學號及四科成績均為不超過300的正整數。

輸出時:第一行輸出兩科總分第一的學號,第二行輸出四科總分第一的學號。 約定在兩位學生成績相同時,優先選擇學號較小的學生;各位學生的學號均不相同。

裁判測試程序樣例:

#include <iostream>
using namespace std;
const int N=80;
struct Student{
  int num;
  int score[4];
};

/* 請在這裏填寫答案 */

int main()
{
  int i, j, k, n;
  bool s2(const Student &, const Student &);
  bool s4(const Student &, const Student &);
  Student st[N];
   cin>>n;
   for(i=0;i<n;i++){
      cin>>st[i].num;
      for(j=0;j<4;j++) cin>>st[i].score[j];
    }
   cout<<select(st, n, s2)<<endl;
   cout<<select(st, n, s4)<<endl;
}

輸入樣例:

3
6 148 150 120 252
5 148 150 117 260
7 145 148 128 287

輸出樣例:

5
7



--------------------------------------------------------------------------------------
                參考代碼
--------------------------------------------------------------------------------------
如果有錯,歡迎指出!

#include <iostream>
using
namespace std; const int N=80; struct Student{ int num; int score[4]; }; /* 請在這裏填寫答案 */ bool s2(const Student &a, const Student &b) { if(a.score[0]+a.score[1]>b.score[0]+b.score[1]) return true; else return false; } bool s4(const Student &a, const Student &b) {
if(a.score[0]+a.score[1]+a.score[2]+a.score[3]>b.score[0]+b.score[1]+b.score[2]+b.score[3]) return true; else return false; } int select (Student st[],int n,bool (*s)(const Student &,const Student &))//主函數使用const,這裏必須有const { int maxNum=0; for(int i=1;i<n;i++) { if(s(st[maxNum],st[i])) continue; else maxNum=i; } return st[maxNum].num; } int main() { int i, j, k, n; bool s2(const Student &, const Student &);//傳遞常引用 bool s4(const Student &, const Student &); Student st[N]; cin>>n; for(i=0;i<n;i++){ cin>>st[i].num; for(j=0;j<4;j++) cin>>st[i].score[j]; } cout<<select(st, n, s2)<<endl; cout<<select(st, n, s4)<<endl; }

 

函數指針(理科實驗班)