Else if condition is being ignored

Viewed 130

The point of this program is to get a 2 digit number input and if the number is smaller or equal to 15, return the number squared, if the number is bigger or equal than 16 and smaller or equal to 30, return the sum of it s digits and if it is bigger or equal to 31, it should return the product of its digits.

This is the code I wrote so far:

#include <iostream>
using namespace std;

int main()
{
    int a;
    cout << "dati a: ";
    cin >> a;
    if (a >= 100 || a)
    {
        cout << "a trebuie sa aiba 2 cifre" << endl
             << "mai dati incercati o data: ";
    }

    if (a <= 15)
    {
        cout << a * a;
    }
    else if (16 <= a <= 30)
    {
        cout << a / 10 + a % 10;
    }
    else if (a >= 31)
    {
        cout << (a / 10) * (a % 10);
    }
}

I compile it and run it and testing goes like this. I give it 10, it returns 100, I give it 23 it returns 5, I give it 29 it returns 11 and the i give it 31 it returns 4, i give it 38, it returns 11. I tend to believe that it goes over the last else if, but i don't know the true reason.

1 Answers

The expression else if (16 <= a <= 30) is not, in all likelihood, doing what you expect it to, it's the same as:

else if ((16 <= a) <= 30)

The first part of the boolean expression is evaluated and, regardless of the result, will make the whole expression true:

else if (1 <= 30) // if it's true

else if (0 <= 30) // if it's false    

I believe you want:

else if (a >= 16 && a <= 30)

Generally speaking, compilers can detect this kind of construct as possibly problematic, though it is not invalid in any way, it is unusual. It's just a matter of setting up your compiler warnings, this will deppend on your specific toolchain, you can find some general instructions here:

Why should I always enable compiler warnings?

Related