我正在尝试编写一个简单的程序来区分偶数和奇数,并根据它们的值对它们应用一个函数,我尝试运行它,并且在我的两个“else”上都得到一个“else without previous if” "语句
我将此提交到我的类(class)帮助论坛,他们说要将我的 if 语句包含在方括号中,我已经这样做了。 (可能不正确)
int output = 0;
if (Input < 0);
{
cout << "0" << endl:
} else
{
if (Input % 2 == 0);
{
output = (Input / 2);
cout << output << endl;
}
}
else
{ if (output = (3 * Input) + 1);
{
cout << output << endl;
}
}
这里是错误:
error: ‘else’ without a previous ‘if’ on both of the else statements
最佳答案
如果正确对齐缩进,问题就会变得很清楚。
if (Input < 0)
{
cout << "0" << endl:
}
else
{
if (Input % 2 == 0)
{
output = (Input / 2);
cout << output << endl;
}
}
else
{
if (output = (3 * Input) + 1)
{
cout << output << endl;
}
}
连续有两个else
。这没有意义。
此外,您不应该使用 ;
关闭 if ()
语句,如果您这样做,您实际上是在告诉编译器这个 if ()
不会触发任何东西(它已关闭,没有关联的代码)。
关于c++ - 我需要帮助来理解这个嵌套的问题 if else,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58035326/