用c语言编写从标准输入读入两组整数(每组不超过20个整数,并且同一组中的整数各不相同),编程求两组整数的交集,即在两组整数中都出现的整数,并按从大到小的顺序输出。若交集为空,则输出“No Intersection”。
时间: 2024-10-08 21:25:39 浏览: 43
在C语言中,你可以使用数组、循环以及嵌套循环来实现这个功能。这里是一个简单的示例程序:
```c
#include <stdio.h>
#include <stdbool.h>
#define MAX_NUMS 20
// 定义函数来找到两个数组的交集
void findIntersection(int arr1[MAX_NUMS], int size1, int arr2[MAX_NUMS], int size2) {
bool intersection[MAX_NUMS] = {false}; // 初始化所有元素为false
for (int i = 0; i < size1; i++) {
for (int j = 0; j < size2 && !intersection[arr1[i]]; j++) { // 如果arr1[i]不在intersection中且在arr2内
if (arr1[i] == arr2[j]) {
intersection[arr1[i]] = true;
break;
}
}
}
// 找出并打印交集
printf("Intersection (from larger to smaller): ");
for (int i = MAX_NUMS - 1; i >= 0 && intersection[i]; i--) {
printf("%d ", i);
}
if (!intersection[0]) {
printf("No Intersection\n");
}
}
int main() {
int size1, size2;
printf("Enter the number of integers in the first group (up to %d): ", MAX_NUMS);
scanf("%d", &size1);
int arr1[MAX_NUMS];
printf("Enter the first group of integers: ");
for (int i = 0; i < size1; i++) {
scanf("%d", &arr1[i]);
}
printf("\nEnter the number of integers in the second group (up to %d): ", MAX_NUMS);
scanf("%d", &size2);
if (size1 > size2) {
int temp[size1];
for (int i = 0; i < size1; i++) {
temp[i] = arr1[i];
}
arr1 = temp;
size1 = size2;
}
int arr2[MAX_NUMS];
printf("Enter the second group of integers: ");
for (int i = 0; i < size2; i++) {
scanf("%d", &arr2[i]);
}
findIntersection(arr1, size1, arr2, size2);
return 0;
}
```
当你运行此程序时,它会提示用户分别输入两个数组的元素数量以及每个数组内的整数。然后计算它们的交集并按照降序输出结果。
阅读全文