C语言找出数组中最大的三个数
以下是C语言代码,用于找出数组中最大的三个数:
#include <stdio.h>
void findTopThree(int arr[], int size){
int first = arr[0];
int second = -1;
int third = -1;
for(int i=1; i<size; i++){
if(arr[i]>first){
third = second;
second = first;
first = arr[i];
}
else if(arr[i]>second){
third = second;
second = arr[i];
}
else if(arr[i]>third){
third = arr[i];
}
}
printf('Top three numbers: %d, %d, %d\n', first, second, third);
}
int main(){
int arr[] = {10, 5, 20, 8, 15, 30};
int size = sizeof(arr)/sizeof(arr[0]);
findTopThree(arr, size);
return 0;
}
该代码首先定义了三个变量,分别代表数组中前三个最大的数。然后使用一个循环遍历整个数组,如果当前元素比第一个变量大,则将第二个和第三个变量向后移动,并将当前元素赋值给第一个变量。如果当前元素比第一个变量小但比第二个变量大,则将第三个变量向后移动,并将当前元素赋值给第二个变量。如果当前元素比第二个变量小但比第三个变量大,则将当前元素赋值给第三个变量。最后,打印出前三个最大的数。
原文地址: https://www.cveoy.top/t/topic/owyY 著作权归作者所有。请勿转载和采集!