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

wha*_*ace 0 c++ boolean-logic if-statement

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

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?");
    }
Run Code Online (Sandbox Code Playgroud)

我的问题是,每次完成for循环,它都会执行"if(crossRes = true)"括号内的语句,即使count永远不会递增.

Ble*_*der 5

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

if (crossRes = true) {
Run Code Online (Sandbox Code Playgroud)

这条线分配crossRestrue并返回true.您正在寻找比较 crossRestrue,这意味着你需要另一个等号:

if (crossRes == true) {
Run Code Online (Sandbox Code Playgroud)

或者更简洁:

if (crossRes) {
Run Code Online (Sandbox Code Playgroud)