How to do if several variables with "or" work?

-3

When I run this program, I choose the integer 1 and enter the two if 's. Why does it enter n==1 and n!=1 at the same time?

#include<stdio.h>

int main(){

    int n; 
    puts("ESCOLA UMA OPCAO");
    puts("1. opcao1");
    puts("2. opcao2");

    scanf("%d", &n);

    ///////////////////////////////////////////////
    if(n==1){
        puts("opcao1");
    }
    ///////////////////////////////////////////////
    if(n==2){
        puts("opcao2");

    }
    ///////////////////////////////////////////////
    if( n!=1 || n!=2)
    {
        puts("erro");
    }

    return 0;
}
    
asked by anonymous 31.01.2016 / 00:57

2 answers

0

For your logic to work, what you want has to put in the last if

ie

int n; 
puts("ESCOLA UMA OPCAO");
puts("1. opcao1");
puts("2. opcao2");

scanf("%d", &n);

///////////////////////////////////////////////
if(n==1){
    puts("opcao1");
}
///////////////////////////////////////////////
if(n==2){
    puts("opcao2");

}
///////////////////////////////////////////////
if( n!=1 && n!=2)
{
    puts("erro");
}

return 0;
    
31.01.2016 / 01:21
1

Another option, in addition to the previous answer, is to use a if-else chained structure:

#include<stdio.h>

int main(){

    int n;
    puts("ESCOLA UMA OPCAO");
    puts("1. opcao1");
    puts("2. opcao2");

    scanf("%d", &n);

    if(n==1){
        puts("opcao1");
    } else if(n==2) {
        puts("opcao2");
    } else {
        puts("erro");
    };
    return 0;
}

Update: A switch structure also works for this case and may eventually make the code more readable:

#include<stdio.h>

int main(){

    int n;
    puts("ESCOLA UMA OPCAO");
    puts("1. opcao1");
    puts("2. opcao2");

    scanf("%d", &n);

    switch (n) {
        // Caso n seja 1
        case 1:
            puts("opcao1");
            break; // termina

        // Caso n seja 2
        case 2:
            puts("opcao2");
            break; // termina

        // Caso contrário
        default:
            puts("erro");
            break; // termina
    };
}
    
31.01.2016 / 01:29