PAT-B 1004. 成绩排名 (20)

题目链接在此

我的思路

用结构体数组保存所有输入,用max和min两个变量(初始化为max=-1,min=101,方便更新)来保存分数的最大值和最小值,max_index和min_index两个变量来保存分数最大值和最小值的结构体成员在结构体数组中的下标,之后输出即可。

我的AC代码

#include<stdio.h>

struct info{
    char name[12];
    char stuNum[12];
    int grade;
}stu[10002];

int main(){

    int n;
    scanf("%d",&n); 

    int max = -1, min = 101; 
    int max_index, min_index;   //分数最高和最低的数组下标 
    for(int i = 0; i < n; i++){
        scanf("%s %s %d",&stu[i].name,&stu[i].stuNum,&stu[i].grade);
        if(stu[i].grade > max){
            max = stu[i].grade;
            max_index = i;
        } 
        if(stu[i].grade < min){
            min = stu[i].grade;
            min_index = i;
        }
    }

    printf("%s %s\n",stu[max_index].name,stu[max_index].stuNum);
    printf("%s %s\n",stu[min_index].name,stu[min_index].stuNum);


    return 0;
} 

《算法笔记》思路

用三个结构体(结构体构成同上)temp,max,min,max.score和min.score初始化为-1和101(作用同上),一遍输入(用temp结构体暂存),一边比较,得出分数最大和最小的结构体,直接赋值给max或者min。

这里让我明白,结构体竟然可以直接赋值,不过有需要注意的地方

简单理解为:没有指针的结构体可以直接赋值(这一块涉及到raw point 和 smart point),有指针的结构体不能直接赋值。具体可见下面两个参考链接。

C语言中结构体直接赋值?
why = operator works on structs without having been defined?

代码

#include<stdio.h>

struct info{
    char name[12];
    char stuNum[12];
    int score;
}temp,max,min;

int main(){

    int n;
    scanf("%d",&n);

    max.score = -1; min.score = 101;

    for(int i = 0; i < n; i++){
        scanf("%s %s %d",temp.name,temp.stuNum,&temp.score);
        if(temp.score > max.score){
            max = temp;
        }
        if(temp.score < min.score){
            min = temp;
        }
    }

    printf("%s %s\n",max.name,max.stuNum);
    printf("%s %s\n",min.name,min.stuNum);

    return 0;
} 
  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值