用c语言写出离散数学中集合的交集并集补集的程序
时间: 2024-03-20 10:44:19 浏览: 58
离散数学实验四编程实现集合的交、并、差和补运算
5星 · 资源好评率100%
好的,下面是一个简单的示例程序:
```c
#include <stdio.h>
#define MAX_SIZE 10
int main() {
int set1[MAX_SIZE], set2[MAX_SIZE], union_set[MAX_SIZE], intersection_set[MAX_SIZE], complement_set[MAX_SIZE];
int n1, n2, i, j, k, flag;
// 输入第一个集合
printf("Enter the size of set 1: ");
scanf("%d", &n1);
printf("Enter the elements of set 1: ");
for (i = 0; i < n1; i++) {
scanf("%d", &set1[i]);
}
// 输入第二个集合
printf("Enter the size of set 2: ");
scanf("%d", &n2);
printf("Enter the elements of set 2: ");
for (i = 0; i < n2; i++) {
scanf("%d", &set2[i]);
}
// 计算并集
k = 0;
for (i = 0; i < n1; i++) {
union_set[k++] = set1[i];
}
for (i = 0; i < n2; i++) {
flag = 1;
for (j = 0; j < n1; j++) {
if (set2[i] == set1[j]) {
flag = 0;
break;
}
}
if (flag) {
union_set[k++] = set2[i];
}
}
printf("The union of set 1 and set 2 is: ");
for (i = 0; i < k; i++) {
printf("%d ", union_set[i]);
}
printf("\n");
// 计算交集
k = 0;
for (i = 0; i < n1; i++) {
for (j = 0; j < n2; j++) {
if (set1[i] == set2[j]) {
intersection_set[k++] = set1[i];
}
}
}
printf("The intersection of set 1 and set 2 is: ");
for (i = 0; i < k; i++) {
printf("%d ", intersection_set[i]);
}
printf("\n");
// 计算补集
k = 0;
for (i = 0; i < n1; i++) {
flag = 1;
for (j = 0; j < n2; j++) {
if (set1[i] == set2[j]) {
flag = 0;
break;
}
}
if (flag) {
complement_set[k++] = set1[i];
}
}
printf("The complement of set 1 with respect to set 2 is: ");
for (i = 0; i < k; i++) {
printf("%d ", complement_set[i]);
}
printf("\n");
return 0;
}
```
程序中定义了 `set1` 和 `set2` 分别表示两个输入的集合,`union_set`、`intersection_set` 和 `complement_set` 分别表示它们的并集、交集和补集。程序先分别输入两个集合,然后按照离散数学中的定义计算并集、交集和补集,并输出结果。
阅读全文