Execution error on switch

1
#include <stdio.h>
#include <math.h>

int main ()
{
int n1, n2, operacao, soma, sub, mult;  
float div;  
    printf("Escolha a opecaracao que deseja realizar: "); 
    scanf("d", &operacao);

    switch(operacao)
    {       
        case 1: '+';
            printf("\nInsira N1: "); scanf("%d", &n1);
            printf("\nInsira N2: "); scanf("%d", &n2);
            soma = n1+n2;
            printf("\n%d + %d = %d", n1, n2, soma);
        break;  

        case 2: '-';
            printf("\n Insira N1: "); scanf("%d", &n1);
            printf("\n Insira N2: "); scanf("%d", &n2);
            sub = n1-n2;
            printf("\n %d - %d = %d", n1, n2, sub);
        break;

        case 3: '*';
            printf("\n Insira N1: "); scanf("%d", &n1);
            printf("\n Insira N2: "); scanf("%d", &n2);
            mult = n1*n2;
            printf("\n %d X %d = %d", n1, n2, mult);    
        break;  

        case 4: '/';
            printf("\n Insira N1: "); scanf("%d", &n1);
            printf("\n Insira N2: "); scanf("%d", &n2);
            div = n1/n2;
            printf("\n %d / %d = %.2f", n1, n2, div);
        break;      
    }

    return 0;
}
    
asked by anonymous 27.09.2018 / 18:27

1 answer

1

One of the errors presented is that you are asking wrong formatting in scanf() . Actually, I think I wanted to ask for the character of the operation, not a number, so I changed that too. And the syntax of case is well wrong is only case and the value you are comparing and : , nothing else. I took advantage of and reduced the scope of variables and eliminated what was unnecessary.

#include <stdio.h>
#include <math.h>

int main() {
    char operacao;
    printf("Escolha a opecaracao que deseja realizar: "); 
    scanf("%c", &operacao);
    switch (operacao) {       
    case '+':
        int n1, n2;
        printf("\nInsira N1: "); scanf("%d", &n1);
        printf("\nInsira N2: "); scanf("%d", &n2);
        printf("\n%d + %d = %d", n1, n2, n1  +n2);
    break;
    case '-':
        int n1, n2;
        printf("\n Insira N1: "); scanf("%d", &n1);
        printf("\n Insira N2: "); scanf("%d", &n2);
        printf("\n %d - %d = %d", n1, n2, n1 - n2);
    break;
    case '*':
        int n1, n2;
        printf("\n Insira N1: "); scanf("%d", &n1);
        printf("\n Insira N2: "); scanf("%d", &n2);
        mult = n1*n2;
        printf("\n %d X %d = %d", n1, n2, n1 * n2);    
    break;
    case '/':
        int n1, n2;
        printf("\n Insira N1: "); scanf("%d", &n1);
        printf("\n Insira N2: "); scanf("%d", &n2);
        printf("\n %d / %d = %.2f", n1, n2, (float)n1 / n2);
    break;      
    }
}

See running on ideone . And no Coding Ground . Also I put it in GitHub for future reference .

    
27.09.2018 / 18:36