在C语言中,如何得到一个整型一维数组的最大值,并输出其下标

如题所述

  这个用假设法就好了,你先假设第一个元素是最大值,然后遍历数组,比最大值大,就重新赋值即可,示例代码如下:

#include<stdio.h>
#define SIZE 8
 
int main(){
    int number[SIZE]={95,45,15,78,84,51,24,12};
    //假设法
int max = number[0];
for (int inx=0; inx!=SIZE; ++inx)
{
if (number[inx] > max) max = number[inx];
else continue;
}
    printf("the max value is:%d\n", max);
}追问

如何得到最大值所对应的数组的下标?

追答

那就在加一句就好了。如下:

#include<stdio.h>
#define SIZE 8
 
int main(){
    int number[SIZE]={15,45,15,78,84,51,24,12};
    //假设法
int max = number[0];
int max_inx = 0;
for (int inx=0; inx!=SIZE; ++inx)
{
if (number[inx] > max) 
{
max = number[inx];
max_inx = inx;
}
else continue;
}
    printf("the max value is:%d, the postion is:%d\n", max, max_inx);
}
温馨提示:答案为网友推荐,仅供参考