// 5-1 找数组最大值及下标
#include<iostream> using namespace std; int main() { int a[10]={17,85,67,83,49,26,92,38,42}; int max,num=0; max=a[0]; for(int i=0;i<10;i++){ if( a[i]>max){ max=a[i]; num=i; } } cout<<"最大值为:"<<max<<"下标为:"<<num<<endl; return 0; }
延伸,最大值 ,最小值及下标
#include<iostream> using namespace std; int main() { int a[10]={17,85,67,83,65,49,26,92,38,42}; int max,num1,min,num2; max=min=a[0]; //初始化最大最小值 num1=num2=0; //初始化下标号为0 for(int i=0;i<10;i++){ if( a[i]>max){ max=a[i]; num1=i; } if (a[i]<min){ min=a[i]; num2=i; } } cout<<"最大值为:"<<max<<"下标为:"<<num1<<endl; cout<<"最小值为:"<<min<<"下标为:"<<num2<<endl; return 0; }