这是我遇到问题的一段代码的极其简化的版本。
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
。您要比较 crossRes
与 true
,这意味着您需要另一个等号:
if (crossRes == true) {
或者更简洁:
if (crossRes) {
关于可能由 if 语句引起的 C++ bool 逻辑错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11729817/