如果要查找的數(shù)在數(shù)組里面有多個(gè)怎么辦?即數(shù)組里有兩個(gè)8
#include <stdio.h>
#include<stdlib.h>
int getIndex(int arr[5],int value)
{
??? int i;
??? int index;
??? for(i=0;i<5;i++)
??? {
????? if(arr[i]==value)?
?????? {
?????????? index=i;
?????????? break;/*一旦查找到8,就跳出循環(huán),輸出index,這種只能查找一次*/
??????? }
?????? else index=-1;
??? }
??? return index;
}
int main()
{
??? int arr[5]={3,8,9,8,6};
??? int value = 8;
??? int index = getIndex(arr,value);????? //這里應(yīng)該傳什么參數(shù)呢?
??? if(index!=-1)
??? {
??????? printf("%d在數(shù)組中存在,下標(biāo)為:%d\n",value,index);????????????
??? }
??? else
??? {
??????? printf("%d在數(shù)組中不存在。\n",value);???
??? }
??? system("pause");
??? return 0;???
}
2018-04-02
你可以直接在查找函數(shù)里直接打印結(jié)果
int getIndex(int arr[5],int value)
{
??? int i;
??? int index=-1;//一開始設(shè)置為-1,假設(shè)沒(méi)找到
??? for(i=0;i<5;i++)
??? {
????? if(arr[i]==value)?
?????? {
? ? ? ? ? ?printf(" ? ?%d",i);//直接輸出要查找數(shù)的下標(biāo)
?????????????index=1;//找到一個(gè)設(shè)置為1
? ? ? ? }
??? }
??? return index;
}
int main()
{
??? int arr[5]={3,8,9,8,6};
??? int value = 8;
??? int index = getIndex(arr,value);????? //arr是要查找的數(shù)組,value是你要查找的數(shù)值
??? if(index!=-1)
??? {
??????? printf("\n%d在數(shù)組中存在,\n",value);?????????????
??? }
??? else
??? {
??????? printf("\n%d在數(shù)組中不存在。\n",value);????
??? }
??? system("pause");
??? return 0;????
}