用c语言随机生成10个五十以内的整数,用函数实现其中的最大数和最小数的位置对换后,再输出调整后的数组
时间: 2024-03-21 17:40:10 浏览: 25
好的,我可以帮你解决这个问题。下面是代码实现:
```c
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define SIZE 10
#define MAX 50
void swap(int *a, int *b) {
int temp = *a;
*a = *b;
*b = temp;
}
void max_min_swap(int arr[], int size) {
int max_index = 0, min_index = 0;
for (int i = 1; i < size; i++) {
if (arr[i] > arr[max_index]) {
max_index = i;
}
if (arr[i] < arr[min_index]) {
min_index = i;
}
}
swap(&arr[max_index], &arr[min_index]);
}
int main() {
int arr[SIZE];
srand((unsigned)time(NULL)); // 设置随机数种子
printf("生成的随机数组为:");
for (int i = 0; i < SIZE; i++) {
arr[i] = rand() % (MAX + 1); // 生成随机数
printf("%d ", arr[i]);
}
printf("\n");
max_min_swap(arr, SIZE);
printf("调整后的数组为:");
for (int i = 0; i < SIZE; i++) {
printf("%d ", arr[i]);
}
printf("\n");
return 0;
}
```
这个程序生成了一个包含10个在50以内随机整数的数组,然后调用 `max_min_swap` 函数来交换最大值和最小值的位置,最后输出调整后的数组。注意,我们使用 `rand()` 函数来生成随机数,使用 `srand()` 函数来设置随机数种子,以便每次运行程序时生成的随机数序列是不同的。
相关推荐
![c](https://img-home.csdnimg.cn/images/20210720083646.png)
![c](https://img-home.csdnimg.cn/images/20210720083646.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.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)