简体   繁体   English

循环计数器失败的C ++

[英]c++ for loop counter failing

Hi I am trying to count the number of zeros after a 1 has occured in a simple 1d array i dont know why the counter is always zero. 嗨,我试图在一个简单的1d数组中发生1之后计算零的数目,但我不知道为什么计数器始终为零。

int main ()
{
    int testarray[9];
    testarray[0] = 0;
    testarray[1] = 0;
    testarray[2] = 1;
    testarray[3] = 1;
    testarray[4] = 0;
    testarray[5] = 0;
    testarray[6] = 0;
    testarray[7] = 1;
    testarray[8] = 1;

    int counter = 0;
    bool white = false;
    bool prevValue =true;
    bool black = true;
    bool check = false;
    int num = 0;

    for (int i = 0; i<8; i++) {
        num = testarray[i];
        if (num == 1)
            white = true;
        else 
            white = false;


        if((white ==true) && (prevValue == false)) {
            if(i == 0) {
                check = true;
                i++;
            }

            else
                check = false;
        }

        else {
            if (check) 
                counter++;
        }
        prevValue = true;

    }

    cout << "Counter: "<<counter;

    return 0;
}

The practical implementation involves using this for loop to detect edges. 实际的实现包括使用此for循环来检测边缘。 I have tried messing with the variables but to no avail. 我试图弄乱变量,但无济于事。 the reason that white =1, and black = 0 is because i am using this loop to solve a vision based problem. 白色= 1,黑色= 0的原因是因为我正在使用此循环来解决基于视觉的问题。 Any help would be apreciated. 任何帮助将不胜感激。

because prevValue is always true : it never come to this block : 因为prevValue始终为true:它永远不会出现在此块中:

if((white ==true) && (prevValue == false)) {
    if(i == 0) {
    check = true;
    i++;
    }

    else
    check = false;
}

so because of this check is never assigned to 'true' so counter is not incremented 所以因为此检查从未分配给'true',所以计数器不会增加

If I have understood all what you need is to find at first 1 and then to count the number of zeroes. 如果我了解全部,那么您需要首先查找1,然后计算零的数量。

It can be done in one statement if to use standard algorithms. 如果使用标准算法,则可以一句话完成。

int counter = std::count( std::find( std::begin( testarray ), std::end( testarray ), 1 ), 
                          std::end( testarray ), 
                          0 );

Because, with this values of the array, check is always false and it need to be true in order to allow counter variable to be incremented as you have written: 因为使用该数组的值,check始终为false,并且必须为true,以便允许计数器变量在您编写时递增:

 if (check) 
     counter++; 

Also, your for loop doesn't reach the value testarray[8], you've to write 另外,您的for循环未达到值testarray [8],您必须编写

 for (int i = 0; i<9; i++)

in order to include from testarray[0] to testarray[9] 为了包括从testarray [0]到testarray [9]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM