Problem to enter Switch

Asked

Viewed 41 times

0

Good afternoon, when running the program below, after typing the third note, the program ends without typing the letter needed to enter the switch. I tested with "i" getting whole number 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;
}
  • See https://answall.com/questions/250506/por-que-n%C3%A3o-can-do-a-read-do-de-Character

1 answer

2


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

You can solve 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); to a getch()

    i = getch();

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

    scanf("%c", &i);
    scanf("%c", &i);

Browser other questions tagged

You are not signed in. Login or sign up in order to post.