在两个条件下查找匹配值

时间:2012-12-25 14:14:44

标签: c arrays

从这段代码:

node [4] = {5,3,2,6};

neighbor [4] = {4,3,2,9};

我必须找到:

node [0] ==匹配来自邻居[0-3]和节点[1]的值==匹配来自邻居的值[0-3]

node [1] ==匹配来自邻居[0-3]和节点[2]的值==匹配来自邻居的值[0-3]

node [2] ==匹配来自邻居[0-3]的值和node [3] ==匹配来自邻居[0-3]的值

如果其中任何一个满足,则打印元素不是......

我试过这段代码,结果找到了元素..

但是当我保持节点[4]相同而邻居[4]是不同的值{4,9,7,9}时;

我仍然将结果作为元素找到

#include<stdio.h>


int main()
{
    int node[4] = {5,3,2,6};
    int neighbor[4] = {4,3,2,9};
    int i,flag=0,k=0;

    for (k=0;k<3;k++){
        for (i = 0; i < 4; i++) {
            if ((node[k]==neighbor[i]) && (node[k+1]==neighbor[i]));
            flag=1;
            break;
        }
    }
    if (flag==0)
    printf("Element not found\n");
    else
    printf("Element  found\n");
}

2 个答案:

答案 0 :(得分:3)

你有一个基本错误

for (k=0;k<3;k++){
        for (i = 0; i < 4; i++) {
            if ((node[k]==neighbor[i]) && (node[k+1]==neighbor[i]));
            flag==1;
            break;
        }

校正

for (k=0;k<3;k++){
        for (i = 0; i < 4; i++) {
            if ((node[k]==neighbor[i]) && (node[k+1]==neighbor[i]));
            flag=1;
            break;
        }

纠正错误        的标志= 1;

答案 1 :(得分:2)

您的问题是;声明之后的if

            if ((node[k]==neighbor[i]) && (node[k+1]==neighbor[i]));

这意味着条件未被使用,flag = 1;始终在运行。删除;

您必须将flag初始化为0:

   int i,flag=0,k=0;

BTW:我要仔细检查你的算法。 node[0] ==match values from neighbor[0-3] and node[1] ==match values from neighbor[0-3]我读到&#34;如果节点0匹配邻居中的任何内容,并且节点1匹配邻居中的任何内容&#34;

但你把它编码为&#34;如果节点X和节点X + 1匹配邻居中的相同的一个值&#34;


您需要的算法非常简单,如果node[X] == anything in neighbor[]构建,则检查是否node[x+1] == anything in neighbor[]

所以对于知道每个数组是数组中4个元素的代码,您可以执行类似这样的操作注意这是未经测试但是它是一个球场概念

int main()
{
    int i;
    for(i = 0; i<3; i++)  // loop from the [0]th to the [2]nd element
    {
        if(is_in_array(node[i], neighbor))   // if the element in node is anywhere in neighbor
            if(is_in_array(node[i]+1, neighbor)) {  // check the next element
                flag = 1;  // if both are in there set the flag
                break;     // and leave the loops early
            }
    } 

    // insert your "if flag print" logic here.

    return 0;
}

int is_in_array(int needle, int haystack[])
{
    int found_it = 0;
    int counter;
    for(counter = 0; counter < sizeof(haystack)/sizeof(int); counter++)
        if(haystack[counter] == needle)
            found_it = 1;
    return found_it;
}