用C语言实现集合的交集运算
时间: 2024-03-24 07:35:39 浏览: 103
这里提供一种基于数组实现的集合交集运算的C语言代码:
```c
#include <stdio.h>
#define MAX_SIZE 100
int main() {
int set1[MAX_SIZE], set2[MAX_SIZE], intersection[MAX_SIZE];
int size1, size2, size_intersection = 0;
// 输入集合1
printf("Enter the size of set1: ");
scanf("%d", &size1);
printf("Enter the elements of set1: ");
for (int i = 0; i < size1; i++) {
scanf("%d", &set1[i]);
}
// 输入集合2
printf("Enter the size of set2: ");
scanf("%d", &size2);
printf("Enter the elements of set2: ");
for (int i = 0; i < size2; i++) {
scanf("%d", &set2[i]);
}
// 计算交集
for (int i = 0; i < size1; i++) {
for (int j = 0; j < size2; j++) {
if (set1[i] == set2[j]) {
intersection[size_intersection] = set1[i];
size_intersection++;
break;
}
}
}
// 输出交集
printf("Intersection of set1 and set2: { ");
for (int i = 0; i < size_intersection; i++) {
printf("%d ", intersection[i]);
}
printf("}\n");
return 0;
}
```
该程序先让用户输入两个集合,然后使用两个嵌套循环计算它们的交集,最后输出交集。需要注意的是,该程序假设输入的集合中不含有重复元素。
阅读全文