用c++写一个运行集合交集和并集的代码
时间: 2023-04-10 11:01:57 浏览: 204
集合的交并差 c++写的 源代码
5星 · 资源好评率100%
好的,以下是用 C 语言编写的集合交集和并集的代码:
```c
#include <stdio.h>
#define MAX_SIZE 100
int main() {
int set1[MAX_SIZE], set2[MAX_SIZE], intersection[MAX_SIZE], union_set[MAX_SIZE];
int size1, size2, intersection_size = 0, union_size = 0;
// 输入集合1
printf("请输入集合1的元素个数:");
scanf("%d", &size1);
printf("请输入集合1的元素:");
for (int i = 0; i < size1; i++) {
scanf("%d", &set1[i]);
}
// 输入集合2
printf("请输入集合2的元素个数:");
scanf("%d", &size2);
printf("请输入集合2的元素:");
for (int i = 0; i < size2; i++) {
scanf("%d", &set2[i]);
}
// 计算交集
for (int i = 0; i < size1; i++) {
for (int j = 0; j < size2; j++) {
if (set1[i] == set2[j]) {
intersection[intersection_size++] = set1[i];
break;
}
}
}
// 计算并集
for (int i = 0; i < size1; i++) {
union_set[union_size++] = set1[i];
}
for (int i = 0; i < size2; i++) {
int is_duplicate = 0;
for (int j = 0; j < size1; j++) {
if (set2[i] == set1[j]) {
is_duplicate = 1;
break;
}
}
if (!is_duplicate) {
union_set[union_size++] = set2[i];
}
}
// 输出结果
printf("集合1:{");
for (int i = 0; i < size1; i++) {
printf("%d", set1[i]);
if (i != size1 - 1) {
printf(", ");
}
}
printf("}\n");
printf("集合2:{");
for (int i = 0; i < size2; i++) {
printf("%d", set2[i]);
if (i != size2 - 1) {
printf(", ");
}
}
printf("}\n");
printf("交集:{");
for (int i = 0; i < intersection_size; i++) {
printf("%d", intersection[i]);
if (i != intersection_size - 1) {
printf(", ");
}
}
printf("}\n");
printf("并集:{");
for (int i = 0; i < union_size; i++) {
printf("%d", union_set[i]);
if (i != union_size - 1) {
printf(", ");
}
}
printf("}\n");
return 0;
}
```
希望这个代码能够帮到你!
阅读全文