用C语言写一个求集合交集和并集的代码
时间: 2024-05-10 20:21:01 浏览: 124
数据结构课程设计—集合运算
```c
#include <stdio.h>
int main() {
int set1[100], set2[100], intersection[100], unionset[200];
int n1, n2, i, j, k, unionlen = 0, intersectionlen = 0;
printf("请输入第一个集合的元素个数:");
scanf("%d", &n1);
printf("请输入第一个集合的元素:");
for (i = 0; i < n1; i++) {
scanf("%d", &set1[i]);
unionset[unionlen++] = set1[i];
}
printf("请输入第二个集合的元素个数:");
scanf("%d", &n2);
printf("请输入第二个集合的元素:");
for (i = 0; i < n2; i++) {
scanf("%d", &set2[i]);
unionset[unionlen++] = set2[i];
}
// 求并集
for (i = 0; i < unionlen; i++) {
for (j = 0; j < i; j++) {
if (unionset[i] == unionset[j]) {
break;
}
}
if (j == i) {
// 没有重复的元素
printf("%d ", unionset[i]);
}
}
printf("是两个集合的并集\n");
// 求交集
for (i = 0; i < n1; i++) {
for (j = 0; j < n2; j++) {
if (set1[i] == set2[j]) {
intersection[intersectionlen++] = set1[i];
break;
}
}
}
printf("两个集合的交集为:");
for (i = 0; i < intersectionlen; i++) {
printf("%d ", intersection[i]);
}
printf("\n");
return 0;
}
```
阅读全文