如何在结构数组中找到最大值?

时间:2014-02-03 17:59:57

标签: c data-structures max

如何获得结构中的最大值?我试图创建一个简单的程序,但我遇到了if语句或变量的问题,因为我无法确定得分最高的获胜者或候选人数。

#include<stdio.h> 
#include<conio.h> 

struct Candidate{ 
float Score; 
short Number; 
}candidate1[5]; 

main(){ 

int i,n,highest; 
for(i=0;i<5;i++){ 

printf("Candidate Number: "); 
scanf("%i",&candidate1[i].Number); 
printf("Score: "); 
scanf("%i",&candidate1[i].Score); 

highest=candidate1[i].Score;    

for (n=0;n<5;n++) 

if (candidate1[i].Score>highest); 
} 
printf("Highest Number: %i\n",highest); 

system("pause");    

}

2 个答案:

答案 0 :(得分:0)

从结构<T>数组中找到类型<S>(double,int,whatever)的最大值的最常见习语如下:

<S> array[numElements]; //defined and allocated earlier.  Has a score `<T> score`
<T> bestScore = array[0].score;
int bestIndex = 0;
int i;
for(i=1;i<numElements;i++) {
    if(array[i].score>bestScore) {
    bestIndex = i;
    bestScore = array[i].score;
    }
}
//do things with bestScore and array[bestIndex];

如果你有一个2D数组,你可以用double for循环替换单个for循环,并为第二个维使用额外的bestIndex变量。

如果数组可能包含0个元素,有时通常会将bestScore设置为最小可能值,并从0循环到numElements

答案 1 :(得分:0)

像这样修复

#include <stdio.h> 
#include <stdlib.h>

struct Candidate {
    float Score;
    short Number;
}candidate1[5];

int main(void){
    int i, n, highest = 0;
    n = sizeof(candidate1)/sizeof(*candidate1);
    for(i=0;i<n;++i){
        printf("Candidate Number: ");
        scanf("%hi", &candidate1[i].Number);
        printf("Score: "); 
        scanf("%f",&candidate1[i].Score);
        if(candidate1[highest].Score < candidate1[i].Score)
            highest = i;
    }
    printf("Highest Number: %f\n", candidate1[highest].Score);

    system("pause");
    return 0;
}