帮我写一个取非空数组中第三大数的c语言程序
时间: 2023-08-28 19:10:28 浏览: 56
以下是一个简单的C语言程序,用于找到非空数组中的第三大数:
```c
#include <stdio.h>
int main() {
int n, i;
printf("Enter the size of array: ");
scanf("%d", &n);
int arr[n];
printf("Enter %d elements of array: ", n);
for (i = 0; i < n; i++)
scanf("%d", &arr[i]);
int max1, max2, max3;
max1 = max2 = max3 = -2147483648; // 初始化为最小值
for (i = 0; i < n; i++) {
if (arr[i] > max1) {
max3 = max2;
max2 = max1;
max1 = arr[i];
} else if (arr[i] > max2 && arr[i] < max1) {
max3 = max2;
max2 = arr[i];
} else if (arr[i] > max3 && arr[i] < max2) {
max3 = arr[i];
}
}
if (max3 == -2147483648) {
printf("There is no third largest element in the array.");
} else {
printf("The third largest element in the array is: %d", max3);
}
return 0;
}
```
该程序首先要求用户输入数组的大小和元素,然后使用循环遍历该数组以找到第三大元素。在遍历过程中,使用三个变量 `max1`、`max2`、`max3` 来存储前三大的元素,如果当前元素大于 `max1`,则将 `max2` 和 `max3` 更新为之前的 `max1` 和 `max2`,并将当前元素赋值给 `max1`。如果当前元素大于 `max2` 且小于 `max1`,则将 `max3` 更新为之前的 `max2`,并将当前元素赋值给 `max2`。如果当前元素大于 `max3` 且小于 `max2`,则将当前元素赋值给 `max3`。最后,如果数组中没有第三大元素,则输出相应的消息;否则,输出第三大元素的值。