finding index of max value in an array in C
I want to find index of max value in array in C.
I write this code example:
maks=0;
for(i=0;i< N * N;开发者_开发技巧i++) {
if(array[i]>maks) {
maks=(int) array[i];
k=i;
}
}
But this isn't work properly.Could you advise me another example please?
Best Regards...
k = 0;
max = array[k];
for (i = 0; i < N * N; ++i)
{
if (array[i] > max)
{
max = (int)array[i];
k = i;
}
}
Should work !
Below function accepts pointer to array with size of the array as arguments and returns the max index.
int max_index(float *a, int n)
{
if(n <= 0) return -1;
int i, max_i = 0;
float max = a[0];
for(i = 1; i < n; ++i){
if(a[i] > max){
max = a[i];
max_i = i;
}
}
return max_i;
}
Usage example,
float a[3] ={1.2,3.2,4.0};
cout<<max_index(a,3)<<endl; //will output 2, because a[2] element is the max
精彩评论