在數(shù)組中有兩個相同數(shù)字時,為何運行結(jié)果不對了?
#include <stdio.h>
int main()
{
int arr[5]={3,12,8,8,6};
? ? int i;
? ? int value =8;
? ? int index;
? ? for(i=0;i<5;i++)
? ? {
? ? ? ?/* 請完善數(shù)組查詢功能 */
? ? if (arr[i] == value){
? ? index = i;
} else{
index = -1;
}? ? ? ? ?
? ? }
? ? printf("index=%d\n",index);
? ? return 0;?
}
這段程序,我將數(shù)組中的8變?yōu)榱藘蓚€,在編譯運行時,輸出結(jié)果反而變成了-1? ? 不知怎么回事。當(dāng)然,也能解決,一個方案是,在index=1;的語句后,增加一個break;輸出結(jié)果為2(第一個出現(xiàn)的符合條件的數(shù)的下標(biāo)).? 第二個方案是直接將else語句刪掉,輸出結(jié)果就會變成3(最后一個出現(xiàn)的符合條件的數(shù)的下標(biāo))。
2018-09-10
if else 在for循環(huán)內(nèi)部,他會一直循環(huán)到數(shù)組的最后一位,所以輸出-1.
2018-09-08
#include <stdio.h>
int getIndex(int arr[5],int value)
{
? ? int i;
? ? int index;
? ? for(i=0;i<5;i++)
? ? {
? ? ? ?/* 請完善數(shù)組查詢功能 */
? ? ? ?if(arr[i]==value)
? ? ? ? {
? ? ? ? ? ? index=i;
? ? ? ? ? ? break;
? ? ? ? } ?
? ? ? ?index=-1;
? ? }
? ? return index;
}
int main()
{
? ? int arr[5]={3,12,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); ? ?
? ? }
? ? return 0; ? ?
}