您的位置:首页 > 其它

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

2017-02-16 15:15 369 查看
题目链接在此

我的思路

用结构体数组保存所有输入,用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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: