c语言实现集合的交、并、差和补运算
时间: 2023-10-20 20:16:35 浏览: 74
C语言中可以使用数组来实现集合的交、并、差和补运算。
交集运算:
```c
#include <stdio.h>
void intersection(int a[], int b[], int n, int m) {
int i, j;
printf("Intersection of two sets:\n");
for (i = 0; i < n; i++) {
for (j = 0; j < m; j++) {
if (a[i] == b[j]) {
printf("%d ", a[i]);
break;
}
}
}
}
int main() {
int a[] = {1, 2, 3, 4, 5};
int b[] = {3, 4, 5, 6, 7};
int n = sizeof(a) / sizeof(a[0]);
int m = sizeof(b) / sizeof(b[0]);
intersection(a, b, n, m);
return 0;
}
```
并集运算:
```c
#include <stdio.h>
void union_set(int a[], int b[], int n, int m) {
int i, j, k = 0;
int c[n + m];
printf("Union of two sets:\n");
for (i = 0; i < n; i++) {
c[k++] = a[i];
}
for (i = 0; i < m; i++) {
for (j = 0; j < n; j++) {
if (b[i] == a[j]) {
break;
}
}
if (j == n) {
c[k++] = b[i];
}
}
for (i = 0; i < k; i++) {
printf("%d ", c[i]);
}
}
int main() {
int a[] = {1, 2, 3, 4, 5};
int b[] = {3, 4, 5, 6, 7};
int n = sizeof(a) / sizeof(a[0]);
int m = sizeof(b) / sizeof(b[0]);
union_set(a, b, n, m);
return 0;
}
```
差集运算:
```c
#include <stdio.h>
void difference(int a[], int b[], int n, int m) {
int i, j, k = 0;
int c[n];
printf("Difference of two sets:\n");
for (i = 0; i < n; i++) {
for (j = 0; j < m; j++) {
if (a[i] == b[j]) {
break;
}
}
if (j == m) {
c[k++] = a[i];
}
}
for (i = 0; i < k; i++) {
printf("%d ", c[i]);
}
}
int main() {
int a[] = {1, 2, 3, 4, 5};
int b[] = {3, 4, 5, 6, 7};
int n = sizeof(a) / sizeof(a[0]);
int m = sizeof(b) / sizeof(b[0]);
difference(a, b, n, m);
return 0;
}
```
补集运算:
```c
#include <stdio.h>
void complement(int a[], int b[], int n, int m) {
int i, j, k = 0;
int c[n];
printf("Complement of set B in set A:\n");
for (i = 0; i < n; i++) {
for (j = 0; j < m; j++) {
if (a[i] == b[j]) {
break;
}
}
if (j == m) {
c[k++] = a[i];
}
}
for (i = 0; i < k; i++) {
printf("%d ", c[i]);
}
}
int main() {
int a[] = {1, 2, 3, 4, 5};
int b[] = {3, 4, 5};
int n = sizeof(a) / sizeof(a[0]);
int m = sizeof(b) / sizeof(b[0]);
complement(a, b, n, m);
return 0;
}
```
阅读全文