How do I make the program identify if the split denominator is zero using switch-case and display an invalidity message in the operation?

Asked

Viewed 60 times

0

I have this exercise to do and everything is going well, but I do not know how to make the program analyze if the denominator is zero and display the message, can help me?

Enunciado do exercício

My code:

#include <stdio.h>
int main(){
int a, b;
char o;

printf("Digite dois valores inteiros:\n");
scanf("%d%d", &a, &b);

printf("\nDigite um caracter de soma, subtracao, divisao ou multiplicacao:\n");
scanf(" %c", &o);

switch (o){
    case '+': printf("\nO resultado da soma eh: %d\n", a + b);
              break;
    case '-': printf("\nO resultado da subtracao eh: %d\n", a - b);
              break;
    case '*': printf("\nO resultado da multiplicacao eh: %d\n", a * b);
              break;
    case '/': printf("\nO resultado da divisao eh: %d\n", a / b);
              break;
    
}
return 0;
}
  • 1

    Have you ever thought of using one if? Something like if (b ==0) { printf("Denominador zero é proibido.\n"); }...

1 answer

2


I can use if inside switch-case?

Can. The case of a switch statement in C is not unique to expressions. You can put statements (statements) within them as well. This includes, for example, a if. The very one break is a statement.

Therefore, it would be enough to check that the denominator is zero using the if in the case of the division. Thus:

#include <stdio.h>

int main(){
    int a, b;
    char o;

    printf("Digite dois valores inteiros:\n");
    scanf("%d%d", &a, &b);

    printf("\nDigite um caracter de soma, subtracao, divisao ou multiplicacao:\n");
    scanf(" %c", &o);

    switch (o){
        case '+':
            printf("\nO resultado da soma eh: %d\n", a + b);
            break;

        case '-':
            printf("\nO resultado da subtracao eh: %d\n", a - b);
            break;

      case '*':
          printf("\nO resultado da multiplicacao eh: %d\n", a * b);
          break;

      case '/':
        if (b == 0) {
            printf("\nDenominador zero é inválido.\n");
            return 1; // Retornar 1 (código de saída padrão para erros.)
        }

        printf("\nO resultado da divisao eh: %d\n", a / b);
        break;
    }

    return 0;
}

See working on Repl.it.

Note in the above code that I have not used a else after the if. I did it because the return eliminates the need for else, since terminates the function, returning from this the value passed. Learn more about this pattern here.

  • 1

    Thank you very much! s2

Browser other questions tagged

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