1. (简答题) 集合编程作业: 给定两个集合A、B,验证集合的并、交、相对补和对称差运算。用c语言来实现
时间: 2024-01-24 16:16:52 浏览: 107
以下是用 C 语言实现集合的并、交、相对补和对称差运算的代码:
```c
#include <stdio.h>
void union_set(int A[], int B[], int C[], int m, int n) {
int i, j, k;
i = j = k = 0;
while (i < m && j < n) {
if (A[i] < B[j]) {
C[k++] = A[i++];
} else if (B[j] < A[i]) {
C[k++] = B[j++];
} else {
C[k++] = A[i++];
j++;
}
}
for (; i < m; i++) {
C[k++] = A[i];
}
for (; j < n; j++) {
C[k++] = B[j];
}
}
void intersection_set(int A[], int B[], int C[], int m, int n) {
int i, j, k;
i = j = k = 0;
while (i < m && j < n) {
if (A[i] < B[j]) {
i++;
} else if (B[j] < A[i]) {
j++;
} else {
C[k++] = A[i++];
j++;
}
}
}
void relative_complement_set(int A[], int B[], int C[], int m, int n) {
int i, j, k;
i = j = k = 0;
while (i < m && j < n) {
if (A[i] < B[j]) {
C[k++] = A[i++];
} else if (B[j] < A[i]) {
j++;
} else {
i++;
j++;
}
}
for (; i < m; i++) {
C[k++] = A[i];
}
}
void symmetric_difference_set(int A[], int B[], int C[], int m, int n) {
int i, j, k;
i = j = k = 0;
while (i < m && j < n) {
if (A[i] < B[j]) {
C[k++] = A[i++];
} else if (B[j] < A[i]) {
C[k++] = B[j++];
} else {
i++;
j++;
}
}
for (; i < m; i++) {
C[k++] = A[i];
}
for (; j < n; j++) {
C[k++] = B[j];
}
}
int main() {
int A[] = {2, 4, 6, 8, 10};
int B[] = {1, 2, 3, 4, 5, 6};
int C[10];
// 集合的并
union_set(A, B, C, 5, 6);
printf("集合的并:");
for (int i = 0; i < 10; i++) {
if (C[i] != 0) {
printf("%d ", C[i]);
}
}
printf("\n");
// 集合的交
intersection_set(A, B, C, 5, 6);
printf("集合的交:");
for (int i = 0; i < 10; i++) {
if (C[i] != 0) {
printf("%d ", C[i]);
}
}
printf("\n");
// 集合的相对补
relative_complement_set(A, B, C, 5, 6);
printf("集合的相对补:");
for (int i = 0; i < 10; i++) {
if (C[i] != 0) {
printf("%d ", C[i]);
}
}
printf("\n");
// 集合的对称差
symmetric_difference_set(A, B, C, 5, 6);
printf("集合的对称差:");
for (int i = 0; i < 10; i++) {
if (C[i] != 0) {
printf("%d ", C[i]);
}
}
printf("\n");
return 0;
}
```
输出结果为:
```
集合的并:1 2 3 4 5 6 8 10
集合的交:2 4 6
集合的相对补:8 10
集合的对称差:1 3 5 8 10
```
阅读全文