查找结构体里的同一项目相同的数据
时间: 2024-03-06 22:49:46 浏览: 10
要查找结构体里同一项目相同的数据,可以使用循环遍历结构体数组,对比每个元素的相同项目是否相同,如果相同则将其记录下来或者进行其他操作。以下是一个示例代码:
```c
#include <stdio.h>
#include <string.h>
#define MAX_SIZE 100
struct student {
char name[20];
int age;
float score;
};
int main() {
struct student students[MAX_SIZE] = {
{"Bob", 18, 89.5},
{"Alice", 20, 92.0},
{"Tom", 18, 87.5},
{"Jack", 19, 90.0},
{"Lucy", 18, 91.5},
{"David", 20, 84.0}
};
int count = 0; // 记录相同项目的数量
for (int i = 0; i < MAX_SIZE - 1; i++) {
for (int j = i + 1; j < MAX_SIZE; j++) {
if (strcmp(students[i].name, students[j].name) == 0) {
// 如果名字相同
printf("Name: %s, Age: %d, Score: %.1f\n", students[i].name, students[i].age, students[i].score);
printf("Name: %s, Age: %d, Score: %.1f\n", students[j].name, students[j].age, students[j].score);
count++;
} else if (students[i].age == students[j].age) {
// 如果年龄相同
printf("Name: %s, Age: %d, Score: %.1f\n", students[i].name, students[i].age, students[i].score);
printf("Name: %s, Age: %d, Score: %.1f\n", students[j].name, students[j].age, students[j].score);
count++;
} else if (students[i].score == students[j].score) {
// 如果分数相同
printf("Name: %s, Age: %d, Score: %.1f\n", students[i].name, students[i].age, students[i].score);
printf("Name: %s, Age: %d, Score: %.1f\n", students[j].name, students[j].age, students[j].score);
count++;
}
}
}
if (count == 0) {
printf("No same projects found.\n");
}
return 0;
}
```
在上面的代码中,我们定义了一个结构体数组 `students`,包含了学生的姓名、年龄和分数。通过两层循环遍历所有的学生,对比他们的名字、年龄和分数是否相同,如果相同则输出信息。最后,如果没有相同项目,输出提示信息。