2、编写函数:求一个含有若干整数的数组中的最大值和最小值,并输出它们的下标。编写一个程序对其进行测试。用C语言。
时间: 2024-12-24 16:39:54 浏览: 53
在C语言中,你可以定义两个函数,一个用于找到数组中的最大值及其索引,另一个用于找到最小值及其索引。以下是实现这两个功能的简单示例:
```c
#include <stdio.h>
#include <limits.h> // 包含INT_MIN和INT_MAX
// 函数:查找最大值及其索引
void findMaxAndMin(int arr[], int n, int* maxIndex, int* minIndex) {
*maxIndex = 0;
*minIndex = 0;
int maxValue = arr[0];
int minValue = INT_MAX;
for (int i = 1; i < n; i++) {
if (arr[i] > maxValue) {
maxValue = arr[i];
*maxIndex = i;
} else if (arr[i] < minValue) {
minValue = arr[i];
*minIndex = i;
}
}
}
// 主函数:测试并打印结果
int main() {
int size;
printf("请输入数组的大小: ");
scanf("%d", &size);
if (size <= 0) {
printf("错误:数组大小必须大于零!\n");
return 1;
}
int arr[size];
printf("请输入数组元素: ");
for (int i = 0; i < size; i++) {
scanf("%d", &arr[i]);
}
int maxIndex, minIndex;
findMaxAndMin(arr, size, &maxIndex, &minIndex);
printf("最大值: %d, 下标: %d\n", arr[maxIndex], maxIndex);
printf("最小值: %d, 下标: %d\n", arr[minIndex], minIndex);
return 0;
}
```
在这个程序中,首先询问用户输入数组的大小和元素,并存储在相应的变量中。然后调用`findMaxAndMin`函数找出最大值和最小值及其索引,最后在主函数中打印结果。如果用户输入的数组大小小于等于0,则程序会显示错误消息。
阅读全文
相关推荐

















