Problem to enter Switch

0

Good afternoon, when executing the program below, after typing the third note, the program ends without typing the letter required to enter the switch. I tested with "i" getting integer and the program worked.

Thank you.

float media_aritmetica(float nota1, float nota2, float nota3);

float media_ponderada(float nota1, float nota2, float nota3);

int main(){

    float nota1, nota2, nota3;
    float m;
    char i;

    printf("Digite o valor da primeira nota:");
    scanf("%f", &nota1);
    printf("Digite o valor da segunda nota:");
    scanf("%f", &nota2);
    printf("Digite o valor da terceira nota:");
    scanf("%f", &nota3);

    printf("Escolha uma das opcoes abaixo:\n");
    printf("A| Media Aritmetica\n");
    printf("B| Media Ponderada\n");
    scanf("%c", &i);

    switch(i){

        case 'A':
            m = media_aritmetica(nota1,nota2,nota3);
            printf("A media aritmetica eh: %.2f", m);
            break;

        case 'B':
            m = media_ponderada(nota1,nota2,nota3);
            printf("A media ponderada eh : %.2f", m);
            break;

        default:
            printf("Letra Invalida!");
            break;
    }
    return 0;
}

float media_aritmetica(float nota1, float nota2, float nota3){
    float media;
    media = (nota1+nota2+nota3)/3;
    return media;
}

float media_ponderada(float nota1, float nota2, float nota3){
    float media;
    media= ((5*nota1)+(3*nota2)+(2*nota3))/5+3+2;
    return media;
}
    
asked by anonymous 19.11.2017 / 16:39

1 answer

1

When you give the enter in the third note, the variable i receives the value of the enter (\ n) that is in the keyboard buffer.

You can solve it in 3 ways:

The first is to put a space before% c because it would only read after space

    scanf(" %c", &i);

Another solution would be to change the scanf ("% c", & i); for a getch ()

    i = getch();

Another would put 2 scanf, one to receive the value of enter and another to receive the value of the

    scanf("%c", &i);
    scanf("%c", &i);
    
19.11.2017 / 17:05