用C语言写出离散数学中集合的交集并集补集的程序
时间: 2024-03-16 08:43:35 浏览: 58
java求集合的并集、交集、补集、差集和对称差集
3星 · 编辑精心推荐
下面是用C语言实现集合的交集、并集和补集的程序:
```c
#include <stdio.h>
int main() {
int set1[100], set2[100], intersection[100], unionSet[200], complement[100], i, j, k, n1, n2, n3 = 0;
// 输入第一个集合
printf("Enter number of elements in set1: ");
scanf("%d", &n1);
printf("Enter elements of set1: ");
for (i = 0; i < n1; i++) {
scanf("%d", &set1[i]);
}
// 输入第二个集合
printf("Enter number of elements in set2: ");
scanf("%d", &n2);
printf("Enter elements of set2: ");
for (i = 0; i < n2; i++) {
scanf("%d", &set2[i]);
}
// 计算交集
k = 0;
for (i = 0; i < n1; i++) {
for (j = 0; j < n2; j++) {
if (set1[i] == set2[j]) {
intersection[k++] = set1[i];
break;
}
}
}
printf("Intersection of set1 and set2: ");
for (i = 0; i < k; i++) {
printf("%d ", intersection[i]);
}
printf("\n");
// 计算并集
k = 0;
for (i = 0; i < n1; i++) {
unionSet[k++] = set1[i];
}
for (i = 0; i < n2; i++) {
for (j = 0; j < n1; j++) {
if (set2[i] == set1[j]) {
break;
}
}
if (j == n1) {
unionSet[k++] = set2[i];
}
}
printf("Union of set1 and set2: ");
for (i = 0; i < k; i++) {
printf("%d ", unionSet[i]);
}
printf("\n");
// 计算补集
k = 0;
for (i = 0; i < n1; i++) {
for (j = 0; j < n2; j++) {
if (set1[i] == set2[j]) {
break;
}
}
if (j == n2) {
complement[k++] = set1[i];
}
}
printf("Complement of set1 with respect to set2: ");
for (i = 0; i < k; i++) {
printf("%d ", complement[i]);
}
printf("\n");
return 0;
}
```
程序首先输入两个集合,然后计算它们的交集、并集和补集,并输出结果。
阅读全文