我必须创建一个函数,打印出一个数组中的所有数字(在' main'中提供),在某个索引内(例如在0-11或2-6之间等)。然后函数必须返回最后一个索引值的值。
例如,给定数组
{8, 3, 6, 7, 9, 5, 3, 8, 6, 7, 4, 5}
如果我输入了数字2
和7
,那么它应该是printf {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;
}
答案 0 :(得分:2)
当您返回data[low]
时,低已经增加1.最后一个低值为high + 1
。 while条件会失败然后退出循环。
所以,你的代码应该是:
return data[high];
答案 1 :(得分:0)
如果您想使用low
变量返回最后一个值,只需执行
return data[--low];
因为在检查条件时,low
的值大于high
的值时会失败。
例如,如果你输入low = 2和high = 7,在最后一次迭代中,low变为8并且打破循环,现在指向活动数组中的值6,因为活动[8] == 6
所以我建议只使用最后一个索引
返回值 return data[high];
答案 2 :(得分:0)
只需 返回数据[高]; 您在高位后将低值增加到1,因此它返回该值。