我有一个包含 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