if里面為什么要加break
#include <stdio.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;//這里為什加上break后結果正確,不加后結果就是不存在
? ? ? ? ?}
? ? ? ? ? else
? ? ? ? ? {
? ? ? ? ? ? ?index=-1;
? ? ? ? ? }
? ? ? ?
? ? ? ?
? ? ? ?
? ? }
? ? return index;
}
int main()
{
? ? int arr[5]={3,12,9,8,6};
? ? int value = 8;
? ? int index = getIndex(arr, value); ? ? ?//這里應該傳什么參數呢?
? ? if(index!=-1)
? ? {
? ? ? ? printf("%d在數組中存在,下標為:%d\n",value,index); ? ? ? ? ? ??
? ? }
? ? else
? ? {
? ? ? ? printf("%d在數組中不存在。\n",value); ? ?
? ? }
? ? return 0; ? ?
}
2015-11-21
加break的意思是,當掃描到相等的數時,就不用接著循環,直接跳出來。如果你不加,那么它不會跳出來,即使找到了要找的數,也沒有辦法把它用某種方式記錄下來,這樣會一直讓i自增上去,直到i = 4,也就是最后一個數,相當于你之前的判斷白做了,總之就是判斷最后一個數,不信你可以把最后一個數改成你要找的數,就可以找到