C语言从键盘输入n个整数,用函数编程实现最大值和最小值的交换,并打印结果。 **输入格式要求:"%d" 提示信息:"Input n(n<=10):" "Input %d numbers:" **输出结果格式要求:"%5d" 提示信息:"Exchange results:"
时间: 2023-07-02 12:09:30 浏览: 93
以下是实现该功能的C语言代码:
```c
#include <stdio.h>
void swap(int *a, int *b) {
int temp = *a;
*a = *b;
*b = temp;
}
int main() {
int n;
printf("Input n(n<=10): ");
scanf("%d", &n);
int nums[n];
printf("Input %d numbers:\n", n);
for (int i = 0; i < n; i++) {
scanf("%d", &nums[i]);
}
int max_index = 0, min_index = 0;
for (int i = 1; i < n; i++) {
if (nums[i] > nums[max_index]) {
max_index = i;
}
if (nums[i] < nums[min_index]) {
min_index = i;
}
}
swap(&nums[max_index], &nums[min_index]);
printf("Exchange results:\n");
for (int i = 0; i < n; i++) {
printf("%5d", nums[i]);
}
return 0;
}
```
运行结果示例:
```
Input n(n<=10): 5
Input 5 numbers:
10 8 20 6 15
Exchange results:
6 8 20 10 15
```
阅读全文