我的代碼問題
我的代碼是這樣寫的,value值在數組范圍內是么有問題的,可是我輸入的值超出了數組范圍后,在編譯器打印的結果卻顯示在“10在數組中存在,下標為35”,而且無論我的value值是多少(數組外),都是下標為35。這是為什么?
#include <stdio.h>
int getIndex(int arr[5],int value)
{
??? int i;
??? int index;
??? for(i=0;i<5;i++)
??? {
?????? /* 請完善數組查詢功能 */
?????? if(arr[i]==value)
?????? {
?????????? return i;
?????? }
???? ?
??? }
??? return index;
}
int main()
{
??? int arr[5]={3,12,9,8,6};
??? int value = 10;
??? int index = getIndex(arr,value);????? //這里應該傳什么參數呢?
??? if(index!=-1)
??? {
??????? printf("%d在數組中存在,下標為:%d\n",value,index);??????????? ?
??? }
??? else
??? {
??????? printf("%d在數組中不存在。\n",value);?? ?
??? }
??? return 0;?? ?
}
2015-11-29
#include <stdio.h>
int getIndex(int arr[5],int value)
{
? ? int i;
? ? int index=-1;//改動的?
? ? for(i=0;i<5;i++)
? ? {
? ? ? ?/* 請完善數組查詢功能 */
? ? ? ?if(arr[i]==value)
? ? ? ?{
? ? ? ? ? ?return i;
? ? ?
? ? ? ?}
? ? ??
? ? }
? ? return index;
}
int main()
{
? ? int arr[5]={3,12,9,8,6};
? ? int value = 10;
? ? int index = getIndex(arr,value); ? ? ?//這里應該傳什么參數呢?
? ? if(index!=-1)
? ? {
? ? ? ? printf("%d在數組中存在,下標為:%d\n",value,index); ? ? ? ? ? ??
? ? }
? ? else
? ? {
? ? ? ? printf("%d在數組中不存在。\n",value); ? ?
? ? }
? ? return 0; ? ?
}
這是我改動了的代碼 就是給index賦值為-1我注釋了 改動 ?你自己找找