简体   繁体   中英

I need help understanding the issue with this nested if else

I'm trying to write a simple program to differentiate even and odd numbers and apply a function to them based upon their values, I try to run this and I get an "else without previous if" on both of my "else" statements

I submitted this to my class help forum and they said to include my if statements with brackets, which I have done. (possibly incorrectly)

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;
    }
}

Here is the error:

error: ‘else’ without a previous ‘if’ on both of the else statements

If you align your indentation properly, the problem becomes clear.

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;
    }
}

There are two else in succession. It makes no sense.

Also, you are not supposed to close if () statements with ; , if you do that you are effectively telling the compiler that this if () doesn't trigger anything (it's been closed with no code associated to it).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM