【浙江大学PAT真题练习乙级】1004 成绩排名 (20分) 真题解析

文章目录

    • 题目描述
    • 思路解析
    • C++实现
    • Python实现

题目描述

  读入 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

思路解析

  就是将姓名、学号、和成绩看作一个整体,然后依据成绩排序就可以了。

C++实现

#include
#include

int main(){
    int n=0;
    scanf("%d",&n);
    struct student_info{
        char name[11];
        char stu_num[11];
        int score;
    };
    struct student_info student, max, min;
    scanf("%s %s %d",&student.name,&student.stu_num,&student.score);
    
    max=min=student;

    for(int i=1;i<n;i++){
        scanf("%s %s %d",&student.name,&student.stu_num,&student.score);
        if (student.score > max.score){
            max = student;
        }
        if (student.score < min.score){
            min = student;
        }
        
    }
    printf("%s %s \n", max.name, max.stu_num);
    printf("%s %s \n", min.name, min.stu_num);
    return 0;
}

Python实现

  在python中用类表示结构体,并且python的一切变量都是对象,变量的存储,采用了引用语义的方式,存储的只是一个变量的值所在的内存地址,而不是这个变量本身。因此需要用copy赋值。数据读入的时候是以空格为分隔符,调用split()函数。

import copy
n = int(input())

class student_info:
    def __init__(self):
        self.name = ""
        self.stu_num = ""
        self.score = 0
        
max_score = student_info()
min_score = student_info()
student = student_info()
name, stu_num, score = input().split(" ")

student.name = name
student.stu_num = stu_num
student.score = int(score)

max_score = copy.copy(student)
min_score = copy.copy(student)

for i in range(n-1):
    name, stu_num, score = input().split(" ")
    student.name = name
    student.stu_num = stu_num
    student.score = int(score)
    
    if int(score) > max_score.score:
        max_score = copy.copy(student)
    if int(score) < min_score.score:
        min_score = copy.copy(student)
        
print(max_score.name, max_score.stu_num)
print(min_score.name, min_score.stu_num)

你可能感兴趣的:(数据结构刷题练习)