c《集合的并、交和差运算》
时间: 2024-03-24 08:38:49 浏览: 20
C语言中,可以使用数组来实现集合的并、交和差运算。具体实现方法如下:
1.集合的并运算
集合的并运算是指将两个集合中的元素合并成一个新的集合,新集合中包含了原来两个集合中所有的元素,但是不包含重复的元素。
示例代码:
```
#include <stdio.h>
int main() {
int set1[] = {1, 2, 3, 4, 5};
int set2[] = {4, 5, 6, 7, 8};
int set3[10];
int i, j, k = 0;
// 集合的并运算
for (i = 0; i < 5; i++) {
set3[k++] = set1[i];
}
for (i = 0; i < 5; i++) {
for (j = 0; j < 5; j++) {
if (set2[i] == set1[j]) {
break;
}
}
if (j == 5) {
set3[k++] = set2[i];
}
}
// 输出结果
printf("set1: ");
for (i = 0; i < 5; i++) {
printf("%d ", set1[i]);
}
printf("\n");
printf("set2: ");
for (i = 0; i < 5; i++) {
printf("%d ", set2[i]);
}
printf("\n");
printf("set3: ");
for (i = 0; i < k; i++) {
printf("%d ", set3[i]);
}
printf("\n");
return 0;
}
```
运行结果为:
```
set1: 1 2 3 4 5
set2: 4 5 6 7 8
set3: 1 2 3 4 5 6 7 8
```
在上面的代码中,我们定义了两个集合set1和set2,然后使用一个数组set3来存储它们的并集。具体实现方法是先将set1中的所有元素添加到set3中,然后遍历set2中的所有元素,如果set2中的元素在set1中没有出现过,就将它添加到set3中。
2.集合的交运算
集合的交运算是指将两个集合中的共同元素提取出来,组成一个新的集合。
示例代码:
```
#include <stdio.h>
int main() {
int set1[] = {1, 2, 3, 4, 5};
int set2[] = {4, 5, 6, 7, 8};
int set3[10];
int i, j, k = 0;
// 集合的交运算
for (i = 0; i < 5; i++) {
for (j = 0; j < 5; j++) {
if (set1[i] == set2[j]) {
set3[k++] = set1[i];
break;
}
}
}
// 输出结果
printf("set1: ");
for (i = 0; i < 5; i++) {
printf("%d ", set1[i]);
}
printf("\n");
printf("set2: ");
for (i = 0; i < 5; i++) {
printf("%d ", set2[i]);
}
printf("\n");
printf("set3: ");
for (i = 0; i < k; i++) {
printf("%d ", set3[i]);
}
printf("\n");
return 0;
}
```
运行结果为:
```
set1: 1 2 3 4 5
set2: 4 5 6 7 8
set3: 4 5
```
在上面的代码中,我们定义了两个集合set1和set2,然后使用一个数组set3来存储它们的交集。具体实现方法是遍历set1中的所有元素,逐个与set2中的元素进行比较,如果有相同的元素就将它添加到set3中。
3.集合的差运算
集合的差运算是指将一个集合中的所有元素去掉另一个集合中的所有元素,组成一个新的集合。
示例代码:
```
#include <stdio.h>
int main() {
int set1[] = {1, 2, 3, 4, 5};
int set2[] = {4, 5, 6, 7, 8};
int set3[10];
int i, j, k = 0;
// 集合的差运算
for (i = 0; i < 5; i++) {
for (j = 0; j < 5; j++) {
if (set1[i] == set2[j]) {
break;
}
}
if (j == 5) {
set3[k++] = set1[i];
}
}
// 输出结果
printf("set1: ");
for (i = 0; i < 5; i++) {
printf("%d ", set1[i]);
}
printf("\n");
printf("set2: ");
for (i = 0; i < 5; i++) {
printf("%d ", set2[i]);
}
printf("\n");
printf("set3: ");
for (i = 0; i < k; i++) {
printf("%d ", set3[i]);
}
printf("\n");
return 0;
}
```
运行结果为:
```
set1: 1 2 3 4 5
set2: 4 5 6 7 8
set3: 1 2 3
```
在上面的代码中,我们定义了两个集合set1和set2,然后使用一个数组set3来存储它们的差集。具体实现方法是遍历set1中的所有元素,逐个与set2中的元素进行比较,如果set1中的元素没有出现在set2中,就将它添加到set3中。