//记录学生的姓名、编号以及总分,输入n,代表学生个数,要求用结构体,
// 用冒泡排序将学生信息按学生总分从低到高排名,将学生信息打印出来;
// 并输入一个总分x,用折半查找查找所有总分为x的学生,并将学生信息打印出来
#include<stdio.h>
#include<stdlib.h>
struct Student {
char name[100];
int id;
int score;
};
struct Student* inStudents(int n);
struct Student* bubbleSort(struct Student* students, int n);
void printStudents(struct Student* students, int n);
//void printOne(struct Student student);
void zhebanSort(struct Student* students, int n,int x);
int main() {
printf("请输入学生个数\:n");
int n;
scanf_s("%d", &n);
struct Student* students = (struct Student*)(malloc(sizeof(struct Student) * n));
if (students == NULL) {
printf("内存分配失败\n");
return 0;
}
students = inStudents(n);
printStudents(students, n);
bubbleSort(students, n);
printStudents(students, n);
printf("输入总分:");
int score;
scanf_s("%d", &score);
zhebanSort(students,n,score);
}
struct Student* inStudents(int n) {
struct Student* students = (struct Student*)(malloc(sizeof(struct Student) * n));
printf("请依次输入学生的name,id和score\n");
int i;
for (i = 0; i < n; i++) {
//gets(students[i].name);
scanf_s("%s", &students[i].name);
scanf_s("%d", &students[i].id);
scanf_s("%d", &(students[i].score));
while (getchar() != '\n');
}
return students;
}
struct Student* bubbleSort(struct Student* students, int n) {
//按照总分从低到高排序
int i;
for (i = n - 1; i > 0; i--) {
int j;
for (j = i; j > 0; j--) {
if (students[j].score < students[j - 1].score) {
struct Student temp = students[j];//为什么这样初始化
students[j] = students[j - 1];
students[j - 1] = temp;
}
}
}
return students;
}
void printStudents(struct Student* students, int n) {
//学生信息打印
int i;
for (i = 0; i < n; i++) {
printf("学生姓名:");
puts(students[i].name);
printf("\t 学生id:%d", students[i].id);
printf("\t 学生score:%d", students[i].score);
printf("\n");
}
}
void zhebanSort(struct Student* students, int n, int x) {
//并输入一个总分x,用折半查找查找所有总分为x的学生,并将学生信息打印出来
//目前是从小到大排序
int i = 0, j = n - 1, mid = (i + j) / 2;
int tag = 0;
while (i < j) {
if (students[mid].score == x) {
tag = 1;
break;
}
else if (students[mid].score > x) {
j = mid;
mid = (i + j) / 2;
}
else {
i = mid;
mid = (i + j) / 2;
}
}
if (tag) {
i = mid - 1, j = mid + 1;
printf("学生姓名:");
puts(students[mid].name);
printf("\t 学生id:%d", students[mid].id);
printf("\t 学生score:%d", students[mid].score);
printf("\n");
while (((i >= 0) && students[i].score == x) || (students[j].score == x) && j < n) {
if (students[i].score == x) {
printf("学生姓名:");
puts(students[i].name);
printf("\t 学生id:%d", students[i].id);
printf("\t 学生score:%d", students[i].score);
printf("\n");
i--;
}
if (students[j].score == x) {
printf("学生姓名:");
puts(students[j].name);
printf("\t 学生id:%d", students[j].id);
printf("\t 学生score:%d", students[j].score);
printf("\n");
j++;
}
}
}
}
标签:struct,students,学生,查找,int,score,总分,Student,printf
From: https://blog.csdn.net/qq_52196203/article/details/136735590