用C++编制一个能演示执行集合的并交和差运算的程序
时间: 2024-06-06 14:09:42 浏览: 97
编制一个演示集合的并、交和差运算的程序
5星 · 资源好评率100%
好的,我明白了,以下是一个简单的C语言程序,可以演示执行集合的并、交和差运算:
#include <stdio.h>
#include <stdlib.h>
void unionset(int set1[], int set2[], int n1, int n2);
void intersectset(int set1[], int set2[], int n1, int n2);
void minusset(int set1[], int set2[], int n1, int n2);
int main()
{
int set1[100], set2[100], n1, n2, choice;
printf("输入集合1的大小:");
scanf("%d", &n1);
printf("依次输入集合1中的元素:");
for (int i = 0; i < n1; i++){
scanf("%d", &set1[i]);
}
printf("\n输入集合2的大小:");
scanf("%d", &n2);
printf("依次输入集合2中的元素:");
for (int i = 0; i < n2; i++){
scanf("%d", &set2[i]);
}
printf("\n1. 集合并运算\n2. 集合交运算\n3. 集合差运算\n请选择需要执行的运算:");
scanf("%d", &choice);
switch (choice) {
case 1:
unionset(set1, set2, n1, n2);
break;
case 2:
intersectset(set1, set2, n1, n2);
break;
case 3:
minusset(set1, set2, n1, n2);
break;
default:
printf("输入错误!\n");
break;
}
return 0;
}
void unionset(int set1[], int set2[], int n1, int n2){
int i, j, k = 0, set3[200];
printf("\n集合1:");
for (i = 0; i < n1; i++) {
printf("%d ", set1[i]);
set3[k] = set1[i];
k++;
}
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]);
set3[k] = set2[i];
k++;
}
}
printf("\n集合2:");
for (i = 0; i < n2; i++) {
printf("%d ", set2[i]);
}
printf("\n集合1和集合2的并集:");
for (i = 0; i < k; i++) {
printf("%d ", set3[i]);
}
}
void intersectset(int set1[], int set2[], int n1, int n2){
int i, j, k = 0, set3[100];
printf("\n集合1:");
for (i = 0; i < n1; i++) {
printf("%d ", set1[i]);
}
printf("\n集合2:");
for (i = 0; i < n2; i++) {
printf("%d ", set2[i]);
}
printf("\n集合1和集合2的交集:");
for (i = 0; i < n1; i++) {
for (j = 0; j < n2; j++) {
if (set1[i] == set2[j]) {
set3[k] = set1[i];
k++;
}
}
}
for (i = 0; i < k; i++) {
printf("%d ", set3[i]);
}
}
void minusset(int set1[], int set2[], int n1, int n2){
int i, j, k = 0, set3[100];
printf("\n集合1:");
for (i = 0; i < n1; i++) {
printf("%d ", set1[i]);
}
printf("\n集合2:");
for (i = 0; i < n2; i++) {
printf("%d ", set2[i]);
}
printf("\n集合1和集合2的差集:");
for (i = 0; i < n1; i++){
for (j = 0; j < n2; j++){
if (set1[i] == set2[j])
break;
}
if (j == n2){
set3[k] = set1[i];
k++;
}
}
for (i = 0; i < k; i++){
printf("%d ", set3[i]);
}
}
以上就是一个简单的C语言程序,可以演示执行集合的并、交和差运算。希望对你有所帮助。
阅读全文