gpt4 book ai didi

c - 我的返回值有问题吗?

转载 作者:行者123 更新时间:2023-11-30 18:50:21 25 4
gpt4 key购买 nike

我必须创建一个函数,打印出数组中某个索引(例如 0-11 或 2-6 等)内的所有数字(在“main”中提供)。然后该函数必须返回最后一个索引值的值。

例如,给定数组

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

如果我输入数字27,那么它应该printf {6 7 9 5 3 8},然后返回8。然而它一直返回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];

关于c - 我的返回值有问题吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40337055/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com