用于循环计数器失败的 C++
c++ for loop counter failing
嗨,我正在尝试计算在一个简单的 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]
相关文章:
- 如果没有malloc,链表实现将失败
- 模板参数替换失败,并且未完成隐式转换
- 具有默认模板参数的多态类的模板推导失败
- 视图中的参数推导失败:take_while
- 链接到自行创建的dll失败
- 带有特殊路径部分的"std::filesystem::weakly_canonical"失败
- GetShortPathName在网络驱动器上使用中文文件夹时失败
- gcc和c++17的过载解析失败
- 为什么使用 P/Invoke 调用 dll 时,某些计算机中的 LoadLibrary 失败?
- 在WSL:configure_file上对config_file的每次调用都失败:配置文件时出现问题
- 使用 GCC 卸载的 OpenMP 卸载失败,并出现"Ptx assembly aborted due to errors"
- 使用cmake从源代码构建MySQL连接器/C++失败(与以前的声明冲突)
- 链接阶段在Ubuntu上失败,但在MacOS上失败
- 从父数组测试用例构造二叉树失败
- LibGit2 SSH身份验证失败
- 如何让LLDB在成功时退出,在失败时等待
- VS2017,C++包含目录与附加包含目录,子文件夹包含失败-但为什么
- 生成MRPT库时cmake配置失败
- 为什么除非添加括号,否则构造函数上的模板替换会失败?
- variadic模板中的模板参数推导失败