5、编写程序实现两个整数集合的基本运算:S1+S2 集合并运算 S1-S2 集合差运算 S1*S2 集合交运算 要求:输入整数集合{2 4 1 3 5}和{2 5 10},输出前者元素个数以及它们进行集合并、差、交运算后的结果。
时间: 2024-04-30 12:18:53 浏览: 109
以下是 Python 代码实现:
```python
set1 = {2, 4, 1, 3, 5}
set2 = {2, 5, 10}
# 集合并运算
union_set = set1.union(set2)
# 集合差运算
difference_set = set1.difference(set2)
# 集合交运算
intersection_set = set1.intersection(set2)
print("集合1的元素个数为:", len(set1))
print("集合并的结果为:", union_set)
print("集合差的结果为:", difference_set)
print("集合交的结果为:", intersection_set)
```
输出结果:
```
集合1的元素个数为: 5
集合并的结果为: {1, 2, 3, 4, 5, 10}
集合差的结果为: {1, 3, 4}
集合交的结果为: {2, 5}
```
相关问题
编写程序实现两个整数集合的基本运算: S1+S2 集合并运算 S1-S2 集合差运算 S1*S2
以下是 Python 代码实现:
```python
# 定义两个集合
S1 = {1, 2, 3}
S2 = {2, 3, 4}
# 集合并运算
print("S1+S2:", S1.union(S2))
# 集合差运算
print("S1-S2:", S1.difference(S2))
# 集合交运算
print("S1*S2:", S1.intersection(S2))
```
输出结果为:
```
S1+S2: {1, 2, 3, 4}
S1-S2: {1}
S1*S2: {2, 3}
```
说明:
- `union()` 方法返回两个集合的并集。
- `difference()` 方法返回 S1 中存在,但 S2 中不存在的元素组成的集合。
- `intersection()` 方法返回两个集合的交集。
用C语言编写程序实现两个整数集合的基本运算: S1+S2 集合并运算 S1-S2 集合差运算 S1*S2
以下是用C语言编写的实现两个整数集合的基本运算的程序:
```c
#include <stdio.h>
int main()
{
int S1[100], S2[100], S3[200], S4[100];
int i, j, k, n1, n2, n3, n4, flag;
printf("Enter the number of elements in set S1: ");
scanf("%d", &n1);
printf("Enter the elements of set S1: ");
for (i = 0; i < n1; i++)
scanf("%d", &S1[i]);
printf("Enter the number of elements in set S2: ");
scanf("%d", &n2);
printf("Enter the elements of set S2: ");
for (i = 0; i < n2; i++)
scanf("%d", &S2[i]);
// Union operation
n3 = 0;
for (i = 0; i < n1; i++)
S3[n3++] = S1[i];
flag = 1;
for (i = 0; i < n2; i++)
{
flag = 1;
for (j = 0; j < n1; j++)
{
if (S2[i] == S1[j])
{
flag = 0;
break;
}
}
if (flag)
S3[n3++] = S2[i];
}
printf("Union of set S1 and S2: ");
for (i = 0; i < n3; i++)
printf("%d ", S3[i]);
printf("\n");
// Difference operation
n4 = 0;
for (i = 0; i < n1; i++)
{
flag = 1;
for (j = 0; j < n2; j++)
{
if (S1[i] == S2[j])
{
flag = 0;
break;
}
}
if (flag)
S4[n4++] = S1[i];
}
printf("Difference of set S1 and S2: ");
for (i = 0; i < n4; i++)
printf("%d ", S4[i]);
printf("\n");
// Intersection operation
n3 = 0;
for (i = 0; i < n1; i++)
{
for (j = 0; j < n2; j++)
{
if (S1[i] == S2[j])
{
S3[n3++] = S1[i];
break;
}
}
}
printf("Intersection of set S1 and S2: ");
for (i = 0; i < n3; i++)
printf("%d ", S3[i]);
printf("\n");
return 0;
}
```
该程序中,定义了4个数组:S1、S2、S3、S4,分别用来存储集合S1、S2、S1和S2的并集、S1和S2的差集。程序首先从用户输入中获取集合S1和S2的元素,然后进行集合并、集合差、集合积的运算,并输出结果。
阅读全文