Use of switch case to choose a function

Asked

Viewed 155 times

0

I would like to use the switch case to choose which function will proceed with the program.

The program has 3 functions: a sum function, another multiplies and the last one is responsible for choosing which function the user will choose. Follows the excerpt from the program:

float escolhaFuncao (int escolha){

 switch (escolha) {
 case 1:
    float SomaDigitos (float soma_A, float soma_B);
    break;
 case 2:
     float Multiplicacao (float num1, float num2);
     break;
 default:
    printf("numero nao permitido");
    break;
 }

return (escolha);
} 

I do not know if this method is the most efficient, actually learning to work with functions, the program is flowing correctly, doing the sum and multiplication, just like to know which method I would use for the user to choose whether to use the function sum or function multiplication.

If you need me to post the complete code, let me know that I edit the post, I did not post soon because my doubt is only in this function.

1 answer

0

this correct way of using the switch case, however I do not know if this program would work, because soma_A,soma_B, num1 and num2 are not being received from nenhnum place (if global variables work, but it is good to avoid global variable). it is necessary to save this result in order to give the return, would be something like

float escolhaFuncao (int escolha,float a, float b){
    float resultado;
    switch (escolha) {
    case 1:
        resultado = SomaDigitos (a, b);// não tem necessidade por o tipo da variavel ao chamar a função
        break;
    case 2:
        resultado = Multiplicacao (a, b);
        break;
    default:
        printf("numero nao permitido");
        break;
    return resultado;
    }

main(){
    ...
    resposta = escolhaFuncao(escolha, a, b)
    ...
    }
  • Dude, I didn’t think of that, I’m gonna test the program with these changes and I’ll be back to let you know if I’ve succeeded

  • I couldn’t, I’ll rewrite all the code and try again

  • really didn’t work.

Browser other questions tagged

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