0

嗨,我试图在一个简单的一维数组中出现 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;
}

实际的实现涉及使用这个 for 循环来检测边缘。我试过弄乱变量,但无济于事。白色 = 1 和黑色 = 0 的原因是因为我正在使用这个循环来解决基于视觉的问题。任何帮助将不胜感激。

4

3 回答 3

0

因为 prevValue 总是 true :它永远不会来到这个块:

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

    else
    check = false;
}

所以因为这个检查永远不会分配给'true'所以计数器不会增加

于 2013-11-14T20:34:26.280 回答
0

如果我已经理解了您所需要的就是首先找到 1,然后计算零的数量。

如果使用标准算法,它可以在一个语句中完成。

int counter = std::count( std::find( std::begin( testarray ), std::end( testarray ), 1 ), 
                          std::end( testarray ), 
                          0 );
于 2013-11-14T20:39:28.190 回答
0

因为,对于数组的这个值,检查总是假的,它需要为真才能允许计数器变量像你写的那样递增:

 if (check) 
     counter++; 

此外,你的 for 循环没有达到值 testarray[8],你必须写

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

为了包含从 testarray[0] 到 testarray[9]

于 2013-11-14T20:41:17.240 回答