1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105
| #include <stdio.h>
#define MAX_SIZE 100
void unionSet(int setA[], int sizeA, int setB[], int sizeB, int resultSet[], int *resultSize); void intersectionSet(int setA[], int sizeA, int setB[], int sizeB, int resultSet[], int *resultSize); void differenceSet(int setA[], int sizeA, int setB[], int sizeB, int resultSet[], int *resultSize);
void printSet(int set[], int size) { printf("{ "); for (int i = 0; i < size; i++) { printf("%d ", set[i]); } printf("}\n"); }
void unionSet(int setA[], int sizeA, int setB[], int sizeB, int resultSet[], int *resultSize) { for (int i = 0; i < sizeA; i++) { resultSet[i] = setA[i]; } *resultSize = sizeA;
for (int i = 0; i < sizeB; i++) { int found = 0; for (int j = 0; j < *resultSize; j++) { if (setB[i] == resultSet[j]) { found = 1; break; } } if (!found) { resultSet[*resultSize] = setB[i]; (*resultSize)++; } } }
void intersectionSet(int setA[], int sizeA, int setB[], int sizeB, int resultSet[], int *resultSize) { *resultSize = 0; for (int i = 0; i < sizeA; i++) { for (int j = 0; j < sizeB; j++) { if (setA[i] == setB[j]) { resultSet[*resultSize] = setA[i]; (*resultSize)++; break; } } } }
void differenceSet(int setA[], int sizeA, int setB[], int sizeB, int resultSet[], int *resultSize) { *resultSize = 0;
for (int i = 0; i < sizeA; i++) { int found = 0; for (int j = 0; j < sizeB; j++) { if (setA[i] == setB[j]) { found = 1; break; } } if (!found) { resultSet[*resultSize] = setA[i]; (*resultSize)++; } } }
int main() { int setA[] = {1, 2, 3, 4, 5}; int sizeA = sizeof(setA) / sizeof(setA[0]);
int setB[] = {4, 5, 6, 7, 8}; int sizeB = sizeof(setB) / sizeof(setB[0]);
int resultSet[MAX_SIZE]; int resultSize;
printf("集合A:"); printSet(setA, sizeA);
printf("集合B:"); printSet(setB, sizeB);
unionSet(setA, sizeA, setB, sizeB, resultSet, &resultSize); printf("并集:"); printSet(resultSet, resultSize);
intersectionSet(setA, sizeA, setB, sizeB, resultSet, &resultSize); printf("交集:"); printSet(resultSet, resultSize);
differenceSet(setA, sizeA, setB, sizeB, resultSet, &resultSize); printf("差集(A - B):"); printSet(resultSet, resultSize);
return 0; }
|