找出一维整型数组中的次最大值。
时间: 2023-06-09 14:07:49 浏览: 94
可以使用两个变量来记录最大值和次大值,遍历一遍数组即可,代码如下:
int findSecondLargest(int arr[], int n) {
int largest = arr[0], secondLargest = INT_MIN;
for(int i = 1; i < n; i++) {
if(arr[i] > largest) {
secondLargest = largest;
largest = arr[i];
} else if(arr[i] > secondLargest && arr[i] != largest) {
secondLargest = arr[i];
}
}
return secondLargest;
}
相关问题
C语言找出一维整型数组中的次最大值。
好的,我知道了,请看下面的C语言代码:
```c
#include <stdio.h>
int main() {
int array[10] = {5, 3, 8, 6, 3, 9, 1, 0, 2, 7};
int max = array[0];
int second_max = array[0];
for(int i = 0; i < 10; i++) {
if(array[i] > max) {
second_max = max;
max = array[i];
} else if(array[i] > second_max && array[i] < max) {
second_max = array[i];
}
}
printf("次最大值为: %d\n", second_max);
return 0;
}
```
这个程序会找出给定整型数组中的次最大值,并将其输出。
2在一个一维整型数组中找出其中最大的数及其下标。c语言
可以使用一个循环遍历整个数组来找出最大值及其下标,代码如下:
```c
#include <stdio.h>
int main() {
int arr[] = {2, 5, 8, 3, 9, 1};
int max = arr[0]; // 假设最大值为数组的第一个元素
int maxIndex = 0; // 假设最大值下标为0
for (int i = 1; i < sizeof(arr)/sizeof(int); i++) {
if (arr[i] > max) {
max = arr[i]; // 更新最大值
maxIndex = i; // 更新最大值下标
}
}
printf("最大值为 %d,下标为 %d\n", max, maxIndex);
return 0;
}
```
输出结果为:
```
最大值为 9,下标为 4
```
相关推荐
![c](https://img-home.csdnimg.cn/images/20210720083646.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)