1. 编写程序,输入10个学生的学号、姓名、性别、年龄,统计其中女生有多少,男生有多少,并根据年龄从小到大对这10个学生重新排序。
程序代码:
#include <stdio.h>
#include <string.h>
#define N 10
typedef struct {
char id[10];
char name[20];
char gender;
int age;
} Student;
// 统计女生和男生人数
void countGender(Student *students, int n, int *femaleCount, int *maleCount) {
for (int i = 0; i < n; i++) {
if (students[i].gender == 'F') {
(*femaleCount)++;
} else if (students[i].gender == 'M') {
(*maleCount)++;
}
}
}
// 按照年龄从小到大排序
void sortStudentsByAge(Student *students, int n) {
for (int i = 0; i < n - 1; i++) {
for (int j = 0; j < n - i - 1; j++) {
if (students[j].age > students[j + 1].age) {
// 交换元素
Student temp = students[j];
students[j] = students[j + 1];
students[j + 1] = temp;
}
}
}
}
int main() {
Student students[N];
int femaleCount = 0;
int maleCount = 0;
// 输入学生信息
for (int i = 0; i < N; i++) {
printf("请输入第%d个学生的学号、姓名、性别、年龄(例如:101 Tom F 18): ", i + 1);
scanf("%s %s %c %d", students[i].id, students[i].name, &students[i].gender, &students[i].age);
}
// 统计女生和男生人数
countGender(students, N, &femaleCount, &maleCount);
printf("女生人数:%d,男生人数:%d\n", femaleCount, maleCount);
// 按照年龄从小到大排序
sortStudentsByAge(students, N);
// 输出排序后的学生信息
printf("按照年龄从小到大排序:\n");
for (int i = 0; i < N; i++) {
printf("%s %s %c %d\n", students[i].id, students[i].name, students[i].gender, students[i].age);
}
return 0;
}
标签:11.23,++,maleCount,students,int,Student,femaleCount From: https://www.cnblogs.com/lml66/p/17909398.html