C语言读入两组整数(每组不超过20个整数,并且同一组中的整数各不相同),编程求两组整数的交集,即在两组整数中都出现的整数,并按从大到小的顺序输出。若交集为空,则什么都不输出。
时间: 2024-10-21 11:10:24 浏览: 14
从标准输入中输入两组整数(每行不超过20个整数,每组整数中元素不重复),合并两组整数,去掉在两组整数中都出现的整数,并按从大到小顺序排序输出(即两组整数集"异或
在C语言中,你可以通过以下步骤编写程序来实现这个功能:
1. 首先,你需要创建两个数组分别存储两组整数,并使用`scanf`函数读取用户输入。
```c
#include <stdio.h>
#define MAX_NUMS_PER_SET 20
int set1[MAX_NUMS_PER_SET];
int set2[MAX_NUMS_PER_SET];
int main() {
int num1, num2;
for (int i = 0; i < MAX_NUMS_PER_SET; i++) {
printf("Enter number %d of the first set (separated by space and no duplicates): ", i + 1);
while (scanf("%d", &num1) == 1) {
if (i == 0 || num1 != set1[i - 1]) { // Check if it's unique
set1[i] = num1;
} else {
break; // Stop reading when duplicate found
}
}
// Skip input for second set since we'll check later
}
// Read second set in a similar manner
for (int i = 0; i < MAX_NUMS_PER_SET; i++) {
scanf("%d", &num2);
set2[i] = num2;
}
// Now find intersection
int common_count = 0;
int common[MAX_NUMS_PER_SET] = {0};
for (int i = 0; i < MAX_NUMS_PER_SET; i++) {
for (int j = 0; j < MAX_NUMS_PER_SET; j++) {
if (set1[i] == set2[j]) {
common[common_count++] = set1[i]; // Store in order, ignoring duplicates
break;
}
}
}
// Sort the common elements from largest to smallest
if (common_count > 0) {
qsort(common, common_count, sizeof(int), compare_ints_descending);
printf("Intersection of the two sets, in descending order:\n");
for (int i = common_count - 1; i >= 0; i--) {
printf("%d ", common[i]);
}
}
return 0;
}
// Custom comparison function to sort integers in descending order
int compare_ints_descending(const void *a, const void *b) {
return (*(const int*)b - *(const int*)a);
}
```
阅读全文