用c语言实现集合的并、交和差运算
时间: 2024-05-01 17:22:55 浏览: 31
集合的并、交和差运算.zip
5星 · 资源好评率100%
以下是用C语言实现集合的并、交和差运算的示例代码:
```c
#include <stdio.h>
#define MAX_SIZE 100
void inputSet(int set[], int *size);
void outputSet(int set[], int size);
int findElement(int set[], int size, int element);
void unionSet(int set1[], int size1, int set2[], int size2, int resultSet[], int *resultSize);
void intersectSet(int set1[], int size1, int set2[], int size2, int resultSet[], int *resultSize);
void differenceSet(int set1[], int size1, int set2[], int size2, int resultSet[], int *resultSize);
int main()
{
int set1[MAX_SIZE], size1, set2[MAX_SIZE], size2, resultSet[MAX_SIZE], resultSize;
printf("Enter elements of set 1:\n");
inputSet(set1, &size1);
printf("Enter elements of set 2:\n");
inputSet(set2, &size2);
printf("Set 1: ");
outputSet(set1, size1);
printf("Set 2: ");
outputSet(set2, size2);
unionSet(set1, size1, set2, size2, resultSet, &resultSize);
printf("Union of set 1 and set 2: ");
outputSet(resultSet, resultSize);
intersectSet(set1, size1, set2, size2, resultSet, &resultSize);
printf("Intersection of set 1 and set 2: ");
outputSet(resultSet, resultSize);
differenceSet(set1, size1, set2, size2, resultSet, &resultSize);
printf("Difference of set 1 and set 2: ");
outputSet(resultSet, resultSize);
return 0;
}
void inputSet(int set[], int *size)
{
int i, n;
printf("Enter size of set: ");
scanf("%d", &n);
printf("Enter %d elements of set:\n", n);
for(i=0; i<n; i++)
{
scanf("%d", &set[i]);
}
*size = n;
}
void outputSet(int set[], int size)
{
int i;
printf("{ ");
for(i=0; i<size; i++)
{
printf("%d ", set[i]);
}
printf("}\n");
}
int findElement(int set[], int size, int element)
{
int i;
for(i=0; i<size; i++)
{
if(set[i] == element)
{
return 1;
}
}
return 0;
}
void unionSet(int set1[], int size1, int set2[], int size2, int resultSet[], int *resultSize)
{
int i;
*resultSize = size1;
for(i=0; i<size2; i++)
{
if(!findElement(set1, size1, set2[i]))
{
resultSet[*resultSize] = set2[i];
(*resultSize)++;
}
}
}
void intersectSet(int set1[], int size1, int set2[], int size2, int resultSet[], int *resultSize)
{
int i;
*resultSize = 0;
for(i=0; i<size1; i++)
{
if(findElement(set2, size2, set1[i]))
{
resultSet[*resultSize] = set1[i];
(*resultSize)++;
}
}
}
void differenceSet(int set1[], int size1, int set2[], int size2, int resultSet[], int *resultSize)
{
int i;
*resultSize = 0;
for(i=0; i<size1; i++)
{
if(!findElement(set2, size2, set1[i]))
{
resultSet[*resultSize] = set1[i];
(*resultSize)++;
}
}
}
```
在该示例代码中,我们首先定义了用于输入、输出、查找元素和进行并、交、差运算的函数。然后,我们在主函数中调用这些函数来实现集合的运算。输入两个集合的元素后,我们分别对它们进行并、交、差运算,并输出结果。
阅读全文