x 要素を含む配列があります。配列内の各要素を検索して、入力値と一致するかどうかを確認したいと考えています。ただし、ルールがあります。検索する整数は、配列の少なくとも 2 つの要素に含まれている必要があり、これらの要素は互いに隣り合っているか、互いに最大 1 つの要素を持っている必要があります。だからこれは私が思いついたものです:
#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;
}
検索する整数の間に 2 つの要素がある場合でも、一致するものが見つかるため、意図したとおりには機能しません。
プログラムの外観の例:
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