用于循环计数器失败的 C++

c++ for loop counter failing

本文关键字:C++ 失败 计数器 循环 用于      更新时间:2023-10-16

嗨,我正在尝试计算在一个简单的 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;
}

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

因为prevValue总是为真:它永远不会出现在这个块:

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

,由于此检查永远不会分配给"true",因此计数器不会增加

如果我明白了,你需要的就是先找到 1,然后计算零的数量。

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

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

因为,对于数组的这个值,check 总是假的,它需要为 true 才能允许计数器变量在你写的时候递增:

 if (check) 
     counter++; 

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

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

为了包含从测试数组[0]到测试数组[9]