[英]Is something wrong with my return value?
我必须创建一个函数,以打印出数组(在“ main”中提供)中的所有数字,并在特定索引内(例如0-11或2-6等)。 然后,该函数必须返回最后一个索引值的值。
例如,给定数组
{8, 3, 6, 7, 9, 5, 3, 8, 6, 7, 4, 5}
如果我输入数字2
和7
,则它应该先打印{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.