簡體   English   中英

我的返回值有問題嗎?

[英]Is something wrong with my return value?

我必須創建一個函數,以打印出數組(在“ main”中提供)中的所有數字,並在特定索引內(例如0-11或2-6等)。 然后,該函數必須返回最后一個索引值的值。

例如,給定數組

{8, 3, 6, 7, 9, 5, 3, 8, 6, 7, 4, 5}

如果我輸入數字27 ,則它應該先打印{6 7 9 5 3 8} ,然后返回8. However it keeps returning 6`。

int index(int data[], int low, int high)
{       
    while(low <= high) {
        printf("%d\n", data[low]);
        low++;
    }

    return data[low];     
}

/* I know I could just put return[high], but i though it  
   wouldn't matter since 'low' keeps incrementing until low == high */

int main()
{       
    int activities[12] = {8, 3, 6, 7, 9, 5, 3, 8, 6, 7, 4, 5}; 
    int low, high;
    int x;

    printf("What is the starting day?  ");
    scanf("%d", &low);
    printf("What is the ending day?  ");
    scanf("%d", &high);

    x = index(activities, low, high);
    printf("\n\nThe function returns this value: %d",x);

    return 0;
}

當您返回data[low] ,low已經增加了1。low的最后一個值將為high + 1 while條件將失敗,然后退出循環。

因此,您的代碼應為:

return data[high];

如果要使用low變量返回最后一個值,則只需執行

return data[--low];

因為在檢查條件時,當low的值大於high的值時,它會失敗。

例如,如果您輸入low = 2和high = 7,則在最后一次迭代中,low變為8並中斷循環,該循環現在指向activity數組中的值6,因為activity [8] == 6

因此,我建議您使用最后一個索引簡單地返回值,

 return data[high];

只是返回數據[高]; 您將高位由低到高依次遞增,因此它會返回該值。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM