简体   繁体   中英

Need help understanding what's going on in my while loop

My program executes just fine, but I have questions about how my while loop is set up.

I know the Boolean values for true and false are 1 and 0, respectively, but I'm not understanding why my output displays the even and odd numbers backwards (to my understanding, it's backwards). Simply put, I don't understand why if ( number % 2 == 0 ) would display that a number is even and when I change it to 1, it displays odd. I'm reading this line as, if (even number equals to false). I don't know if that's where I'm going wrong. What's the correct way to read this line?

The way I have my code set up now displays the numbers correctly, I'm just not understanding why. Can anyone help?

// Program indefinitely displays an even
// or odd number until a negative number
// is entered.
#include <iostream>
using namespace std;

int main()
{

    int number;

    cout << "Please enter a number: ";
    cin >> number;

    while ( number >= 0 )
    {
        if ( number % 2 == 0 )
        {
            cout << number << " is even \n";
            cout << "Please enter a number: ";
            cin >> number;
        }
        else
        {
            cout << number << " is odd \n";
            cout << "Please enter a number: ";
            cin >> number;
        }
    }

    cout << "Thank you. \n";
    return 0;
}

number % 2 is 0 if number divides 2 (ie is even ), 1 if number is positive and does not divide 2 (ie is odd ), and -1 if number is negative and does not divide 2 (ie is odd ). (The last point must be the case from C++11 onwards).

So, since 0 == 0 is true , number % 2 == 0 is true if, and only if, number is even .

So you've written if ( number % 2 == 0 ) to trap all even cases, and the else traps the odd cases.

Testing if ( number % 2 == 1 ) is only a test for positive oddness, but older C++ standards allow this to be true for negative number .

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