c++ - 我需要帮助来理解这个嵌套的问题 if else

标签 c++

我正在尝试编写一个简单的程序来区分偶数和奇数,并根据它们的值对它们应用一个函数,我尝试运行它,并且在我的两个“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/

相关文章:

c++ - Visual Studio 使用多线程 DLL 发布应用程序文件

c++ - 无法从 'TCHAR [260]' 转换为 'std::basic_string<wchar_t,std::char_traits<wchar_t>,std::allocator<wchar_t>>

c++ - fftw3 的常量正确性

c++ - Win32 : Create a class with standard cursor (IDC_CROSS)

c++ - 因为 std::swap(s1, s2) 就足够了,所以 string::swap 可以忽略吗?

c++ - 带有 boost::asio 的 TCP 服务器,线程池的可扩展性与无堆栈协程

c++ - 使用 `createProcess()` 调用 Webots 时传递参数

c++ - 使用汇编代码在 OpenGL 中呈现视频时出错

c++ - Qt代理模型使用示例

c++ - 传递枚举数组是什么意思?