可能由 if 语句引起的 C++ bool 逻辑错误

标签 c++ if-statement boolean-logic

这是我遇到问题的一段代码的极其简化的版本。

int i = 0;
int count = 0;
int time = 50;
int steps = 1000;
double Tol = 0.1;
bool crossRes = false;
bool doNext = true;

for (int i=0; i<steps; i++) {

//a lot of operations are done here, I will leave out the details, the only
//important things are that "dif" is calculated each time and doNext either
//stays true or is switched to false

    if (doNext = true) {
        if (dif <= Tol) count++;
        if (count >= time) {
            i = steps+1;
            crossRes = true;
        }
    }
}

    if (crossRes = true) {
        printf("Nothing in this loop should happen if dif is always > Tol 
               because count should never increment in that case, right?");
    }

我的问题是,每次完成 for 循环时,它都会执行“if (crossRes = true)”括号内的语句,即使计数从未递增也是如此。

最佳答案

你犯了一个常见的(而且非常令人沮丧的)错误:

if (crossRes = true) {

此行将 crossRes 分配给 true 并返回 true。您要比较 crossRestrue,这意味着您需要另一个等号:

if (crossRes == true) {

或者更简洁:

if (crossRes) {

关于可能由 if 语句引起的 C++ bool 逻辑错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11729817/

相关文章:

c++ - 使用 PAHO c/cpp 在代理后面使用 MQTT

C++ 重载或监视解引用运算符(在指针上)

python - 如何在正则表达式中使用 bool OR

c++ - 使用 union 与多个结构

c++ - sclite (SCTK) 安装,文件无法识别,文件格式无法识别,Cygwin

c - 带有 "if"的循环无法正常工作

c++ - if 赋值/语句在 C++ 中意味着什么

java - if-else语句去错误的条件语句java?

python - 如何重新排序 bool 逻辑以更快地短路?

java - 内置逻辑的返回语句