IF multiple does not work

0

I've tried this and it always works, enter the number that is

if(i==(1|2|3|4|5)){

    printf("me ha llegado un numero del 1 al 5");
 }

alternatives?

    
asked by Alber 15.04.2017 в 14:15
source

3 answers

3

| is the operator bitwise or .

This means that it takes the two operands and makes the or binary, bit by bit . So, 1|2 is 0001|0010 that returns 0011 (that is 3).

Also, apart from the precedence of the operators, you first do the | of all the numbers (which returns 7 and then you compare the result with i ).

As the comments have suggested, to check that an integer is in a range of numbers, it is most usual to check that it is greater than or equal to the lower limit of the range and that it is also less than or equal to the upper limit of the range, that is:

if ((i >= 1) && (i <= 5))

In case the list of numbers is not correlated, you can use the construction switch-case :

switch (i) {
  case 1:
    // No se pone break para que no salte
  case 3:
  case 4:
    ... Aquí es 1, 3, ó 4
    break;
  default:
    ... Aquí no es 1, 3 ni 4.
 }
    
answered by 15.04.2017 / 14:35
source
0

Do the if so

if( i==1 || i==2 || i==3 || i==4 || i==5 )){
    printf("me ha llegado un numero del 1 al 5");
 }else{
    printf("número no encontrado")
 }

The other option is to use a switch for each case from 1 to 5 and a default (the entire range of numbers different from those established in the cases) that indicates that the number entered is not valid.

    
answered by 15.04.2017 в 19:32
-2

Any number that you enter, other than zero, will enter the IF. The check that your code is doing is to evaluate true or true or true or true or true equal to true against i then any number other than zero is true and therefore enters. Test with if (i> = 1 & i < = 5). I hope it serves you.

    
answered by 15.04.2017 в 14:45