B1004. 成绩排名 (20)

题目描述:

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

输入格式:每个测试输入包含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 

思路:

(1)用结构体存储学生数据,用分数作为下标(不存在学生分数相同的情况),读入数据的同时记录最大最小值。

        之后直接输出所要信息;用变量max、min分别记录最大最小值,先分别赋值-1,101,方便进行更新;

        使用strcpy() 复制字符串。 要加头文件#include <cstring>。

(2)可直接定义temp、max、min三个结构体变量用于读入数据和存储最大最小值;

(1)代码如下:

#include <cstdio>
#include <cstring>

struct student 
{
	char name[15];
	char id[15];
	int score;
}	st[110];

int main()
{
	int n, max = -1, min = 101;            //只要有数据输入就会更新;
	char name[15], id[15];
	int score;
	
	scanf ("%d", &n);
	for (int i = 0; i < n; i++)
	{
		scanf ("%s%s%d", name, id, &score);
		strcpy (st[score].name, name);			//将字符复制到结构体中; 
		strcpy (st[score].id, id);
		if (score >= max)		max = score;				//记录最高分; 
		if (score <= min)		min = score;				//记录最低分 
	}
	
	printf ("%s %s\n", st[max].name, st[max].id);
	printf ("%s %s\n", st[min].name, st[min].id);
 	return 0;
}

(2)代码如下:

#include <cstdio>

struct student 
{
	char name[15];
	char id[15];
	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.id, &temp.score);
		if (temp.score > max.score) 	max = temp;        //结构体之间可直接赋值; 
		if (temp.score < min.score)     min = temp;
	}
	
	printf ("%s %s\n", max.name, max.id);
	printf ("%s %s\n", min.name, min.id);

 	return 0;
}


猜你喜欢

转载自blog.csdn.net/privilage/article/details/79928955