2

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.

anastaciu
  • 23,467
  • 7
  • 28
  • 53
alex
  • 31
  • 2
  • 1
    `16 <= a <= 30` doesn't do what you think it does. – πάντα ῥεῖ Apr 29 '21 at 10:36
  • `(16 <= a <= 30) -> (a >= 16 && a <= 30)`. `16 <= a <= 30` is always true because both 1 and 0 are less than 30. – Wais Kamal Apr 29 '21 at 10:38
  • Does this answer your question? [Why can't we do three-way comparison in C++?](https://stackoverflow.com/q/56526264/11683) – GSerg Apr 29 '21 at 10:44
  • This is redundant. `a` is an integer, so `a <= 15` already covers everything below 16. So you just want `if (a <= 15) ... else if (a <= 30) ... else ...` – paddy Apr 29 '21 at 10:48

1 Answers1

5

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?

anastaciu
  • 23,467
  • 7
  • 28
  • 53