简体   繁体   English

我的返回值有问题吗?

[英]Is something wrong with my return value?

I had to make a function that prints out all the numbers in an array (provided in 'main'), within a certain index (eg between 0-11, or 2-6, etc). 我必须创建一个函数,以打印出数组(在“ main”中提供)中的所有数字,并在特定索引内(例如0-11或2-6等)。 Then the function has to return the value of the last index value. 然后,该函数必须返回最后一个索引值的值。

For example, given the array 例如,给定数组

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

If I input the numbers 2 and 7 , then it should printf {6 7 9 5 3 8} , and then return 8. However it keeps returning 6`. 如果我输入数字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;
}

When you return data[low] , low is already incremented by 1. The last value of low would be high + 1 . 当您返回data[low] ,low已经增加了1。low的最后一个值将为high + 1 The while condition would fail and then come out of the loop. while条件将失败,然后退出循环。

So, your code should be: 因此,您的代码应为:

return data[high];

If you want to return the last value using the low variable you can simply do 如果要使用low变量返回最后一个值,则只需执行

return data[--low];

Because while checking the condition it fails when the value of low is greater than the value of high . 因为在检查条件时,当low的值大于high的值时,它会失败。

For example the if you enter low = 2 and high = 7, in the last iteration low become 8 and break the loop which now points to value 6 in activities array since activities[8] == 6 例如,如果您输入low = 2和high = 7,则在最后一次迭代中,low变为8并中断循环,该循环现在指向activity数组中的值6,因为activity [8] == 6

So I would suggest to simply return the value using the last index that is, 因此,我建议您使用最后一个索引简单地返回值,

 return data[high];

Just return data[high]; 只是返回数据[高]; You incremented low to one after high so it returns that value. 您将高位由低到高依次递增,因此它会返回该值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM