请你用C语言编程实现:给定两个集合A、B,验证集合的并、交、相对补和对称差运算
时间: 2024-05-17 17:17:41 浏览: 108
下面是一个简单的示例程序,用于演示如何在 C 语言中实现集合的并、交、相对补和对称差运算。
```c
#include <stdio.h>
#define MAX_SIZE 100
void print_set(int set[], int size);
void set_union(int set1[], int size1, int set2[], int size2, int result[]);
void set_intersection(int set1[], int size1, int set2[], int size2, int result[]);
void set_difference(int set1[], int size1, int set2[], int size2, int result[]);
void set_symmetric_difference(int set1[], int size1, int set2[], int size2, int result[]);
int main()
{
int set1[MAX_SIZE], set2[MAX_SIZE], result[MAX_SIZE];
int size1, size2;
// 输入集合1
printf("Enter the size of set A: ");
scanf("%d", &size1);
printf("Enter the elements of set A: ");
for (int i = 0; i < size1; i++) {
scanf("%d", &set1[i]);
}
// 输入集合2
printf("Enter the size of set B: ");
scanf("%d", &size2);
printf("Enter the elements of set B: ");
for (int i = 0; i < size2; i++) {
scanf("%d", &set2[i]);
}
// 集合运算
printf("\nSet A: ");
print_set(set1, size1);
printf("Set B: ");
print_set(set2, size2);
printf("\nUnion of A and B: ");
set_union(set1, size1, set2, size2, result);
print_set(result, size1+size2);
printf("Intersection of A and B: ");
set_intersection(set1, size1, set2, size2, result);
print_set(result, size1+size2);
printf("Difference of A and B: ");
set_difference(set1, size1, set2, size2, result);
print_set(result, size1+size2);
printf("Symmetric difference of A and B: ");
set_symmetric_difference(set1, size1, set2, size2, result);
print_set(result, size1+size2);
return 0;
}
// 打印集合
void print_set(int set[], int size)
{
printf("{ ");
for (int i = 0; i < size; i++) {
printf("%d ", set[i]);
}
printf("}\n");
}
// 集合并运算
void set_union(int set1[], int size1, int set2[], int size2, int result[])
{
int i, j, k;
for (i = 0; i < size1; i++) {
result[i] = set1[i];
}
k = i;
for (j = 0; j < size2; j++) {
int found = 0;
for (i = 0; i < size1; i++) {
if (set2[j] == set1[i]) {
found = 1;
break;
}
}
if (!found) {
result[k] = set2[j];
k++;
}
}
}
// 集合交运算
void set_intersection(int set1[], int size1, int set2[], int size2, int result[])
{
int i, j, k;
k = 0;
for (i = 0; i < size1; i++) {
for (j = 0; j < size2; j++) {
if (set1[i] == set2[j]) {
result[k] = set1[i];
k++;
break;
}
}
}
}
// 集合相对补运算
void set_difference(int set1[], int size1, int set2[], int size2, int result[])
{
int i, j, k;
k = 0;
for (i = 0; i < size1; i++) {
int found = 0;
for (j = 0; j < size2; j++) {
if (set1[i] == set2[j]) {
found = 1;
break;
}
}
if (!found) {
result[k] = set1[i];
k++;
}
}
}
// 集合对称差运算
void set_symmetric_difference(int set1[], int size1, int set2[], int size2, int result[])
{
int i, j, k;
set_difference(set1, size1, set2, size2, result);
k = size1 - size2;
set_difference(set2, size2, set1, size1, &result[k]);
}
```
这个程序定义了一个 `print_set` 函数用于打印集合,以及四个函数分别实现了集合的并、交、相对补和对称差运算。在主函数中,我们先输入两个集合,然后分别调用这四个函数进行集合运算,并打印结果。注意,这个程序中假设集合中的元素都是整数,并且集合中不会有重复元素。如果需要处理其他类型的元素或者允许重复元素,需要对程序进行相应的修改。
阅读全文