1004 成绩排名 (20 分)

读入 n(>0)名学生的姓名、学号、成绩,分别输出成绩最高和成绩最低学生的姓名和学号。

输入格式:
每个测试输入包含 1 个测试用例,格式为

第 1 行:正整数 n
第 2 行:第 1 个学生的姓名 学号 成绩
第 3 行:第 2 个学生的姓名 学号 成绩
… … …
第 n+1 行:第 n 个学生的姓名 学号 成绩
其中姓名和学号均为不超过 10 个字符的字符串,成绩为 0 到 100 之间的一个整数,这里保证在一组测试用例中没有两个学生的成绩是相同的。

输出格式:
对每个测试用例输出 2 行,第 1 行是成绩最高学生的姓名和学号,第 2 行是成绩最低学生的姓名和学号,字符串间有 1 空格。

输入样例:

3
Joe Math990112 89
Mike CS991301 100
Mary EE990830 95

输出样例:

Mike CS991301
Joe Math990112
#include <stdio.h>
int main()
{
    int n,i;
    scanf("%d",&n);
    char maxname[21];
    char maxnumber[21];
    int maxscore = -1;
    
    char minname[21];
    char minnumber[21];
    int minscore = 101;
    
    for(i = 0;i<n;i++){
        char name[21];
        char number[21];
        int sco;
        scanf("%s %s %d",name,number,&sco);
        if(sco>maxscore){
            maxscore = sco;
            strcpy(maxname,name);
            strcpy(maxnumber,number);
        }
        if(sco<minscore){
            minscore =sco;
            strcpy(minname,name);
            strcpy(minnumber,number);
        }
    }
    printf("%s %s
",maxname,maxnumber);
    printf("%s %s
",minname,minnumber);
    return 0;
}

法2

题目中需要注意的:

1、由于不知道有多少学生,所以不能直接定义struct Student student[n];要开辟动态结构体的空间,student=(struct Student )malloc(nsizeof(struct Student));。

2、用malloc要引入头文件#include<stdlib.h>。

#include <stdio.h>
#include <stdlib.h>

struct Student{
  char name[11];
  char number[11];
  int score;
};

int main(){
  int n=0;
  int max=0;
  int min=0;
  scanf("%d",&n);
  if(n==0){
    return 0;
  }
  struct Student *student;
  student=(struct Student *)malloc(n*sizeof(struct Student));
  for(int i=0;i<n;i++){
    scanf("%s %s %d",&student[i].name,&student[i].number,&student[i].score);
  }
  for(int j=0;j<n;j++){
    if(student[j].score>student[max].score)
      max=j;
    if(student[j].score<student[min].score)
      min=j;
  }
  printf("%s %s
",student[max].name,student[max].number);
  printf("%s %s
",student[min].name,student[min].number);
  return 0;
}
欢迎查阅
原文地址:https://www.cnblogs.com/gh110/p/11892802.html