求任意两个整数集合的交集、并集和差集C++代码
时间: 2023-04-09 07:01:24 浏览: 248
交集:
```c
#include <stdio.h>
int main() {
int set1[] = {1, 2, 3, 4, 5};
int set2[] = {3, 4, 5, 6, 7};
int n1 = sizeof(set1) / sizeof(set1[0]);
int n2 = sizeof(set2) / sizeof(set2[0]);
int i, j;
printf("Intersection: ");
for (i = 0; i < n1; i++) {
for (j = 0; j < n2; j++) {
if (set1[i] == set2[j]) {
printf("%d ", set1[i]);
break;
}
}
}
return 0;
}
```
并集:
```c
#include <stdio.h>
int main() {
int set1[] = {1, 2, 3, 4, 5};
int set2[] = {3, 4, 5, 6, 7};
int n1 = sizeof(set1) / sizeof(set1[0]);
int n2 = sizeof(set2) / sizeof(set2[0]);
int i, j;
printf("Union: ");
for (i = 0; i < n1; i++) {
printf("%d ", set1[i]);
}
for (i = 0; i < n2; i++) {
for (j = 0; j < n1; j++) {
if (set2[i] == set1[j]) {
break;
}
}
if (j == n1) {
printf("%d ", set2[i]);
}
}
return 0;
}
```
差集:
```c
#include <stdio.h>
int main() {
int set1[] = {1, 2, 3, 4, 5};
int set2[] = {3, 4, 5, 6, 7};
int n1 = sizeof(set1) / sizeof(set1[0]);
int n2 = sizeof(set2) / sizeof(set2[0]);
int i, j;
printf("Difference: ");
for (i = 0; i < n1; i++) {
for (j = 0; j < n2; j++) {
if (set1[i] == set2[j]) {
break;
}
}
if (j == n2) {
printf("%d ", set1[i]);
}
}
return 0;
}
```
阅读全文