定义一个函数,将数组中的最大值与最小值交换位置(要求用指针完成)
时间: 2024-03-12 19:46:22 浏览: 32
好的,以下是一个简单的实现:
```c
#include <stdio.h>
void swap(int *a, int *b) {
int temp = *a;
*a = *b;
*b = temp;
}
void swap_max_min(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[] = {3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5};
int size = sizeof(arr) / sizeof(arr[0]);
printf("Before swapping: ");
for (int i = 0; i < size; i++) {
printf("%d ", arr[i]);
}
printf("\n");
swap_max_min(arr, size);
printf("After swapping: ");
for (int i = 0; i < size; i++) {
printf("%d ", arr[i]);
}
printf("\n");
return 0;
}
```
这个程序定义了一个 `swap` 函数,用于交换两个整数的值。然后定义了一个 `swap_max_min` 函数,用于找到数组中的最大值和最小值的下标,并将它们交换。在 `main` 函数中,我们测试了这个函数,输出了交换前和交换后的数组。
相关推荐
![](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)