編与程序,输入 20 个数并存人数组,将下标值为偶数的元素按降序排列,输出该数组。
时间: 2024-03-02 10:54:10 浏览: 27
好的,这是一个比较简单的程序。以下是实现该程序的示例代码:
```c++
#include <iostream>
#include <algorithm>
using namespace std;
int main() {
const int n = 20;
int a[n];
for (int i = 0; i < n; i++) {
cin >> a[i];
}
sort(a, a + n, greater<int>());
for (int i = 0; i < n; i += 2) {
cout << a[i] << " ";
}
cout << endl;
return 0;
}
```
程序首先定义了一个长度为20的整型数组a,然后通过循环读入20个整数存入数组a中。接下来使用STL库中的sort函数将数组a中下标为偶数的元素按降序排列。最后再次循环遍历数组a,输出下标为偶数的元素即可。
注意:在编写程序时,要确保输入的20个数不超过数组a的长度,否则会导致数组越界错误。
相关问题
編与程序,输入 20 个数并存人数组,将下标值为偶数的元素按降序排列,输出该数组。 c语言
好的,以下是使用C语言实现的程序示例:
```c
#include <stdio.h>
#include <stdlib.h>
int main(void) {
const int n = 20;
int a[n];
int i, j, temp;
for (i = 0; i < n; i++) {
scanf("%d", &a[i]);
}
for (i = 0; i < n; i += 2) {
for (j = i + 2; j < n; j += 2) {
if (a[i] < a[j]) {
temp = a[i];
a[i] = a[j];
a[j] = temp;
}
}
}
for (i = 0; i < n; i++) {
printf("%d ", a[i]);
}
printf("\n");
return 0;
}
```
程序首先定义了一个长度为20的整型数组a,然后通过循环读入20个整数存入数组a中。接下来使用冒泡排序将数组a中下标为偶数的元素按降序排列。最后再次循环遍历数组a,输出数组a的所有元素即可。
注意:在编写程序时,要确保输入的20个数不超过数组a的长度,否则会导致数组越界错误。
编写c语言程序,输入20个数并存入数组,将下标值为偶数的元素按降序排列,输出该数组
以下是实现上述需求的C语言程序:
```c
#include <stdio.h>
// 交换两个元素
void swap(int *a, int *b) {
int temp = *a;
*a = *b;
*b = temp;
}
int main() {
int arr[20];
int i, j;
// 输入20个数并存入数组
printf("请输入20个数:\n");
for (i = 0; i < 20; i++) {
scanf("%d", &arr[i]);
}
// 将下标值为偶数的元素按降序排列
for (i = 0; i < 20; i += 2) {
for (j = i + 2; j < 20; j += 2) {
if (arr[i] < arr[j]) {
swap(&arr[i], &arr[j]);
}
}
}
// 输出该数组
printf("排序后的数组为:\n");
for (i = 0; i < 20; i++) {
printf("%d ", arr[i]);
}
printf("\n");
return 0;
}
```
程序运行时,会依次提示输入20个数,并输出排序后的数组。其中,下标值为偶数的元素按降序排列。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)