小明最近喜欢玩一款新游戏。在该游戏中,需要组建队伍去完成任务以获取奖励。小明挑出了所有的队员(每个人能力不同),需要一个函数挑出队长(能力最强的队员)。 函数接口定义: void showCaptain(TeamMember team[], int n); 参数说明:team中从下标0开始存放n个TeamMember,n>0。 函数功能:找出队长并输出其各项信息 裁判测试程序样例: #include<stdio.h> #include<stdlib.h> #define NAME_LEN 100 #define SEX_LEN 6 typedef struct { int id;//身份证号码 char lastname[NAME_LEN+1];//姓 char firstname[NAME_LEN+1];//名 char sex[SEX_LEN];//性别 double ability; } TeamMember; void showCaptain(TeamMember team[], int n); int main() { TeamMember *team; int n; int i; scanf("%d",&n); team = (TeamMember *)malloc(n*sizeof(TeamMember)); for(i=0;i<n;i++) { scanf("%d %s %s %s %lf",&team[i].id,team[i].lastname, team[i].firstname, team[i].sex, &team[i]. ability); } showCaptain(team, n); return 0; } /* 您提交的代码将放置在这里 */ 输入样例: 3 123456 zhang san male 100 123457 li si female 200.5 123458 wang ming male 159.1 输出样例: 123457 li si female 200.50 代码长度限制 16 KB 时间限制 400 ms 内存限制 64 MB C (gcc) 1 测试用例 上一题 提交本题作答 下一题
时间: 2024-04-07 20:27:56 浏览: 177
下面是一份可行的代码实现:
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define NAME_LEN 100
#define SEX_LEN 6
typedef struct {
int id; // 身份证号码
char lastname[NAME_LEN+1]; // 姓
char firstname[NAME_LEN+1]; // 名
char sex[SEX_LEN]; // 性别
double ability; // 能力值
} TeamMember;
void showCaptain(TeamMember team[], int n)
{
int i, max_index = 0;
double max_ability = 0.0;
for (i = 0; i < n; i++) {
if (team[i].ability > max_ability) {
max_index = i;
max_ability = team[i].ability;
}
}
printf("%d %s %s %s %.2lf\n", team[max_index].id, team[max_index].lastname,
team[max_index].firstname, team[max_index].sex, team[max_index].ability);
}
int main()
{
TeamMember *team;
int n;
int i;
scanf("%d", &n);
team = (TeamMember *) malloc(n * sizeof(TeamMember));
for (i = 0; i < n; i++) {
scanf("%d %s %s %s %lf", &team[i].id, team[i].lastname, team[i].firstname,
team[i].sex, &team[i].ability);
}
showCaptain(team, n);
free(team);
return 0;
}
```
函数 `showCaptain` 的实现思路是遍历整个队伍,找到能力值最大的队员,然后输出其信息。
注意在输出 `double` 类型的能力值时,需要使用 `%.2lf` 的格式化字符串,将其保留两位小数。同时,在程序结束时需要释放动态分配的内存。
阅读全文