gpt4 book ai didi

C - 在数组中搜索彼此接近的相同值?

转载 作者:太空宇宙 更新时间:2023-11-04 04:47:16 24 4
gpt4 key购买 nike

我有一个包含 x 个元素的数组。我想搜索数组中的每个元素,看看它是否与我的输入值匹配。但是,有一条规则:要搜索的整数必须在数组的至少两个元素中并且这些元素必须彼此相邻,或者彼此之间最多有一个元素。所以这就是我想出的:

#include <stdio.h>

int main(void)
{

int elements;
int input;
int i;

printf("How many elements in the array? ");
scanf("%d", &elements);

int array[elements];

printf("Ok, please input %d integer values: ", elements);

for(i=0; i < elements; i++)
{
scanf("%d", &array[i]);
}

printf("Which integer should I search for? ");
scanf("%d", &input);

for(i=0; i < elements; i++)
{
if((array[i] == input && array[i+1] == input) || (array[i] == input && array[i+2] == input))
{
printf("Match!\n");
break;
}

else
{
printf("Match not found!\n");
break;
}
}

getchar();
getchar();
getchar();

return 0;
}

它没有按预期工作,因为如果我搜索的整数之间有两个元素,它仍会找到匹配项。

程序的外观示例:

Array: 1, 2, 3, 4, 5, 5
Integer to search for: 5
Match found! // 5 and 5 are next to each other

Array: 1, 2, 3, 2, 4, 5
Integer to search for: 2
Match found! // 2 and 2 has only one element (3) between each other

Array: 1, 2, 1, 1, 2, 5
Integer to search for: 2
Match not found! // 2 and 2 has more than one element between each other

最佳答案

很奇怪。在我的 gcc 4.6.3

显示

How many elements in the array? 6
Ok, please input 6 integer values: 1
2
1
1
2
5
Which integer should I search for? 2
Match not found!

关于C - 在数组中搜索彼此接近的相同值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19635815/

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