c语言实现集合的交并差运算
时间: 2023-09-27 19:11:32 浏览: 274
集合的并交补差
以下是 C 语言实现集合的交并差运算的代码示例:
```c
#include <stdio.h>
#define MAX_SIZE 100
void inputSet(int set[], int *size);
void printSet(int set[], int size);
void unionSet(int set1[], int size1, int set2[], int size2, int resultSet[], int *resultSize);
void intersectSet(int set1[], int size1, int set2[], int size2, int resultSet[], int *resultSize);
void diffSet(int set1[], int size1, int set2[], int size2, int resultSet[], int *resultSize);
int main() {
int set1[MAX_SIZE], set2[MAX_SIZE], resultSet[MAX_SIZE];
int size1, size2, resultSize;
printf("Enter elements of set 1:\n");
inputSet(set1, &size1);
printf("Enter elements of set 2:\n");
inputSet(set2, &size2);
printf("\nSet 1: ");
printSet(set1, size1);
printf("Set 2: ");
printSet(set2, size2);
// Union
unionSet(set1, size1, set2, size2, resultSet, &resultSize);
printf("\nUnion: ");
printSet(resultSet, resultSize);
// Intersection
intersectSet(set1, size1, set2, size2, resultSet, &resultSize);
printf("Intersection: ");
printSet(resultSet, resultSize);
// Difference
diffSet(set1, size1, set2, size2, resultSet, &resultSize);
printf("Difference (set1 - set2): ");
printSet(resultSet, resultSize);
return 0;
}
void inputSet(int set[], int *size) {
printf("Enter size of set: ");
scanf("%d", size);
printf("Enter elements of set:\n");
for (int i = 0; i < *size; i++) {
scanf("%d", &set[i]);
}
}
void printSet(int set[], int size) {
printf("{ ");
for (int i = 0; i < size; i++) {
printf("%d ", set[i]);
}
printf("}\n");
}
void unionSet(int set1[], int size1, int set2[], int size2, int resultSet[], int *resultSize) {
int index = 0;
for (int i = 0; i < size1; i++) {
resultSet[index++] = set1[i];
}
for (int i = 0; i < size2; i++) {
int found = 0;
for (int j = 0; j < size1; j++) {
if (set2[i] == set1[j]) {
found = 1;
break;
}
}
if (!found) {
resultSet[index++] = set2[i];
}
}
*resultSize = index;
}
void intersectSet(int set1[], int size1, int set2[], int size2, int resultSet[], int *resultSize) {
int index = 0;
for (int i = 0; i < size1; i++) {
for (int j = 0; j < size2; j++) {
if (set1[i] == set2[j]) {
resultSet[index++] = set1[i];
break;
}
}
}
*resultSize = index;
}
void diffSet(int set1[], int size1, int set2[], int size2, int resultSet[], int *resultSize) {
int index = 0;
for (int i = 0; i < size1; i++) {
int found = 0;
for (int j = 0; j < size2; j++) {
if (set1[i] == set2[j]) {
found = 1;
break;
}
}
if (!found) {
resultSet[index++] = set1[i];
}
}
*resultSize = index;
}
```
在这个示例中,我们通过 `inputSet` 函数从标准输入中获取两个集合,并通过 `unionSet`、`intersectSet` 和 `diffSet` 函数计算它们的并、交和差,最后通过 `printSet` 函数输出结果。请注意,此示例假定输入的集合中的元素没有重复。
阅读全文