定义一个student的结构体,并创建一个结构体数组,并用下表数据对其初始化,输出成绩最高那个同学的学号和姓名。(姓名占15个宽度,学号占4个宽度)。
Num Name Sex Score
101 Li ping M 45
102 Zhang ping M 62
103 He fang F 92
104 Cheng ling F 87
105 Wang ming M 58
#include <stdio.h>
#include <iostream>
#include <vector>
using namespace std;
struct student
{
int num;
string name;
char sex;
int score;
};
int main()
{
struct student p[5] = {{101,"Li ping",'M', 45},{102,"Zhang ping",'M', 62},{103,"He fang",'F', 92},{104,"Cheng ling",'F', 87},{105,"Wang ming",'M', 58}};
printf("Num Name Sex Score\n");
for(int i = 0;i<5;i++)
{
cout << p[i].num <<" "<<p[i].name << " "<<p[i].sex << " "<<p[i].score <<endl;
}
return 0;
}
代码实现如下,望采纳
#include <iostream>
#include <string>
// 定义一个学生结构体
struct Student {
int num;
std::string name;
char sex;
int score;
};
int main() {
// 创建学生结构体数组并初始化
Student students[] = {
{101, "Li ping", 'M', 45},
{102, "Zhang ping", 'M', 62},
{103, "He fang", 'F', 92},
{104, "Cheng ling", 'F', 87},
{105, "Wang ming", 'M', 58}
};
// 初始化最高分学生信息
int maxScore = 0;
Student maxScoreStudent = {};
// 遍历学生数组,找到成绩最高的学生
for (const auto &student : students) {
if (student.score > maxScore) {
maxScore = student.score;
maxScoreStudent = student;
}
}
// 输出学号和姓名,注意使用 std::setw 设置输出宽度
std::cout << std::setw(4) << maxScoreStudent.num << " " << std::setw(15) << maxScoreStudent.name << std::endl;
return 0;
}