上面这个代码用while循环
时间: 2024-09-09 12:14:26 浏览: 38
c代码-阶乘求和(while循环)
5星 · 资源好评率100%
当然可以,如果你希望用`while`循环代替`for`循环来寻找数组的最大值和最小值,你可以这样做:
```c
#include <stdio.h>
#include <limits.h>
double find_average(int arr[], int index, int* max_index, int* min_index) {
int max_value = INT_MIN;
int min_value = INT_MAX;
*max_index = 0;
*min_index = 0;
while (index < sizeof(arr)/sizeof(arr[0])) {
if (arr[index] > max_value) {
max_value = arr[index];
*max_index = index;
} else if (arr[index] < min_value) {
min_value = arr[index];
*min_index = index;
}
index++;
}
return (double)(max_value + min_value) / 2;
}
int main() {
int numbers[] = {5, 2, 9, 1, 7};
int size = sizeof(numbers) / sizeof(numbers[0]);
int max_index, min_index;
double avg = find_average(numbers, 0, &max_index, &min_index);
if (avg != -1) {
printf("The average of the minimum value at index %d and the maximum value at index %d is: %.2f\n", min_index, max_index, avg);
}
return 0;
}
```
在这个版本中,我们添加了两个指向当前最大值和最小值索引的指针,并在`while`循环中更新它们。这样,在找到最大值和最小值后,可以在`main()`函数里直接获取对应的索引。
阅读全文