简体   繁体   中英

Why wont my if else statement work

The first two statements run with the given number input but the third statement doesn't run.

#include <iostream>
using namespace std;

int main()
{

    double X;

    cout << "Please pick a number from -10 to 10";

    cin >> X;

    if ((-3 <= X)&&( X <= 2))
        cout << "Y = " << ( X * X) + (2 * X) -3 << endl;

    else if ((2 < X)&&(X <= 10))
        cout << "Y = " << (5 * X) + 7 << endl;

    else if ((X > 10)&&(X < -3))
        cout << "Y = " << 0 << endl;

    return 0;
}

When I choose -10 or 11 the result I receive is just an end program not a "Y = 0 ".

 if ((X > 10)&&(X < -3))

At a time X can't be X > 10 and X < -3 so it'll always return false.

So it can never go inside (3rd) if condition.

You might want to use || instead of && so that if anyone is true it can go inside if condition:

if ((X > 10)||(X < -3))

The answer is that one number cannot be greater then 10 and lower than -3 in one time. For example 20 is greater then 10 but also greater then -3. You can't find this 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