c++ - 为什么我在 for 循环中收到 'Else without previous if' 错误?

标签 c++ syntax if-statement

我是 C++ 的新手,盯着我的(可能很糟糕的)代码有一段时间了,无法弄清楚它有什么问题。

我正在尝试遍历 if 和 else 语句的几次迭代,并且一定是在做一些语法错误的事情——因为它显示了“else without a previous if”的编译器错误

这是一个类,我正在努力解决这个问题,但如果你看到我忽略的一些明显的东西,我很想知道。

谢谢!

for (i = 0; i < iterationsNum; i++){
if (charlieAlive == 0) // Aarron's shot
        {
        if (aaronShot() == 1)
        charlieAlive = 1;
        }       
else (charlieAlive == 1 && bobAlive == 0);{         
        if (aaronShot() == 1)
        bobAlive = 1;
        }
else (charlieAlive == 1 && bobAlive == 1 && aaronAlive == 0);{
        cout << "Aaron is the Winner!\n";
        totalShot++;
        aaronCounter++;
        }
continue;



if (charlieAlive == 0 && aaronAlive ==0) // Bob's shot
        {
        if (bobShot() == 1) 
        charlieAlive = 1;
        }
else (charlieAlive == 1 && aaronAlive == 0);{
        if (bobShot() == 1)
        aaronAlive = 1;
        }
else (charlieAlive == 1 && aaronAlive == 1 && bobAlive == 0);{
        cout << "Bob is the Winner!\n";
        bobCounter++;
        totalShot++;
        }
continue;


if (charlieAlive == 0 && bobAlive == 0) // Charlie's shot   
        {
        bobAlive = 1;
        }
else (charlieAlive == 0 && bobAlive == 1 && aaronAlive == 0);{          
        aaronAlive = 1;
        totalShot++;
        }
else (charlieAlive == 0 && bobAlive == 1 && aaronAlive == 1);{
        cout << "Charlie is the Winner!\n";
        }
continue;

最佳答案

else 不接受任何条件,但你已经这样写了:

else (charlieAlive == 1 && bobAlive == 0);  //else : (notice semicolon)

它没有按照您的预期去做。

您想这样做:

else if (charlieAlive == 1 && bobAlive == 0)  //else if : (semicolon removed)

注意区别。

此外,最多可以有一个 else block ,与 if block 相关联 或者一串 if, else-if, else-if block 。也就是说,你可以这样写:

if (condition) {}
else {}

或者,

if (condition0) {}
else if (condition1) {}
else if (condition2) {}
else if (condition3) {}
else if (condition4) {}
else {}

在任何情况下,else block 总是 最后一个 block 。之后,如果您编写另一个 else block ,那将是一个错误。

除此之外,您还在错误的位置使用了分号。还解决了这个问题:

else (charlieAlive == 1 && bobAlive == 0); <---- remove this semicolon!

希望对您有所帮助。


选择一本好的 C++ 入门书籍。以下是针对所有级别的一些建议。

关于c++ - 为什么我在 for 循环中收到 'Else without previous if' 错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14995454/

相关文章:

javascript - 动态改变javascript中if语句中的条件

c++ - 逐行读取 QString 的最佳方法

Python 相当于 c++ find_if

linux - shell脚本中的 "-le"是什么?

c++ - 奇怪的条件语法

Scala 扩展双箭头

r - 在 R 中嵌套 ifelse

c++ - WideCharToMultiByte - 对于 Shift-JIS 代码页,所需的大小和写入的字节数不同

c++ - Qt 如何找出 closeEvent(QCloseEvent *event) 从哪里触发

c++ - 阻止 QMenu 在其 QAction 之一被触发时关闭