请用C语言实现:输入两个集合A、B,验证集合的并、交、相对补和对称差运算
时间: 2024-01-27 14:05:37 浏览: 75
集合运算_集合运算问题_
5星 · 资源好评率100%
以下是使用C语言实现输入两个集合A、B,验证集合的并、交、相对补和对称差运算的示例代码:
```c
#include <stdio.h>
#include <stdlib.h>
#define MAX_SIZE 100
void input_set(int set[], int *size) {
printf("请输入集合大小:");
scanf("%d", size);
printf("请输入集合元素:");
for (int i = 0; i < *size; i++) {
scanf("%d", &set[i]);
}
}
void print_set(int set[], int size) {
printf("{ ");
for (int i = 0; i < size; i++) {
printf("%d ", set[i]);
}
printf("}\n");
}
void union_set(int set1[], int size1, int set2[], int size2, int result[], int *size) {
int i, j, k;
for (i = 0; i < size1; i++) {
result[i] = set1[i];
}
k = size1;
for (i = 0; i < size2; i++) {
for (j = 0; j < size1; j++) {
if (set2[i] == set1[j]) {
break;
}
}
if (j == size1) {
result[k++] = set2[i];
}
}
*size = k;
}
void intersection_set(int set1[], int size1, int set2[], int size2, int result[], int *size) {
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];
break;
}
}
}
*size = k;
}
void difference_set(int set1[], int size1, int set2[], int size2, int result[], int *size) {
int i, j, k;
k = 0;
for (i = 0; i < size1; i++) {
for (j = 0; j < size2; j++) {
if (set1[i] == set2[j]) {
break;
}
}
if (j == size2) {
result[k++] = set1[i];
}
}
*size = k;
}
void symmetric_difference_set(int set1[], int size1, int set2[], int size2, int result[], int *size) {
int i, j, k;
k = 0;
for (i = 0; i < size1; i++) {
for (j = 0; j < size2; j++) {
if (set1[i] == set2[j]) {
break;
}
}
if (j == size2) {
result[k++] = set1[i];
}
}
for (i = 0; i < size2; i++) {
for (j = 0; j < size1; j++) {
if (set2[i] == set1[j]) {
break;
}
}
if (j == size1) {
result[k++] = set2[i];
}
}
*size = k;
}
int main() {
int set1[MAX_SIZE], set2[MAX_SIZE], result[MAX_SIZE], size1, size2, result_size;
input_set(set1, &size1);
input_set(set2, &size2);
printf("\n集合A:");
print_set(set1, size1);
printf("集合B:");
print_set(set2, size2);
union_set(set1, size1, set2, size2, result, &result_size);
printf("集合A和B的并集为:");
print_set(result, result_size);
intersection_set(set1, size1, set2, size2, result, &result_size);
printf("集合A和B的交集为:");
print_set(result, result_size);
difference_set(set1, size1, set2, size2, result, &result_size);
printf("集合A和B的相对补集为:");
print_set(result, result_size);
symmetric_difference_set(set1, size1, set2, size2, result, &result_size);
printf("集合A和B的对称差集为:");
print_set(result, result_size);
return 0;
}
```
运行结果示例:
```
请输入集合大小:5
请输入集合元素:1 2 3 4 5
请输入集合大小:4
请输入集合元素:3 4 5 6
集合A:{ 1 2 3 4 5 }
集合B:{ 3 4 5 6 }
集合A和B的并集为:{ 1 2 3 4 5 6 }
集合A和B的交集为:{ 3 4 5 }
集合A和B的相对补集为:{ 1 2 }
集合A和B的对称差集为:{ 1 2 6 }
```
阅读全文