1用C语言随机生成一组(20个)两位整数,完成如下功能: (1)分别统计输出奇偶数的个数,并求出偶数和、奇数平均值; (2)编写排序函数sort(int a[],int n)实现将数组从小到大排序,在主函数中调用sort函数对这组(20个)整数进行排序,输出排序结果; (3)不重新排序的前提下(即:前后对调),把数组改为从大到小排序并输出结果。
时间: 2024-01-09 20:06:13 浏览: 35
好的,我会尽力回答你的问题。以下是用C语言实现你所需要的功能的代码:
```c
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define SIZE 20
void sort(int a[], int n); // 声明排序函数
int main()
{
int arr[SIZE]; // 存储随机生成的20个数
int even_count = 0; // 偶数个数
int odd_count = 0; // 奇数个数
int even_sum = 0; // 偶数和
float odd_avg = 0.0; // 奇数平均值
// 用系统时间作为随机数生成器的种子,防止每次生成的随机数都相同
srand((unsigned)time(NULL));
// 随机生成20个两位整数
for (int i = 0; i < SIZE; i++) {
arr[i] = rand() % 90 + 10; // 生成10~99之间的随机数
printf("%d ", arr[i]); // 输出生成的数
if (arr[i] % 2 == 0) { // 如果是偶数
even_count++; // 偶数个数+1
even_sum += arr[i]; // 偶数和加上这个数
} else { // 如果是奇数
odd_count++; // 奇数个数+1
odd_avg += (arr[i] - odd_avg) / odd_count; // 更新奇数平均值
}
}
printf("\n");
printf("偶数个数:%d\n", even_count);
printf("奇数个数:%d\n", odd_count);
printf("偶数和:%d\n", even_sum);
printf("奇数平均值:%f\n", odd_avg);
// 对数组从小到大排序
sort(arr, SIZE);
printf("从小到大排序结果:");
for (int i = 0; i < SIZE; i++) {
printf("%d ", arr[i]);
}
printf("\n");
// 把数组改为从大到小排序
for (int i = 0; i < SIZE / 2; i++) {
int temp = arr[i];
arr[i] = arr[SIZE - 1 - i];
arr[SIZE - 1 - i] = temp;
}
printf("从大到小排序结果:");
for (int i = 0; i < SIZE; i++) {
printf("%d ", arr[i]);
}
printf("\n");
return 0;
}
// 排序函数
void sort(int a[], int n)
{
for (int i = 0; i < n - 1; i++) {
for (int j = i + 1; j < n; j++) {
if (a[i] > a[j]) {
int temp = a[i];
a[i] = a[j];
a[j] = temp;
}
}
}
}
```
希望这个代码能够帮到你!如果你有任何其他问题,欢迎再次向我提问。
相关推荐
![c](https://img-home.csdnimg.cn/images/20210720083646.png)
![pptx](https://img-home.csdnimg.cn/images/20210720083543.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)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)