How to do an operation using the CHAR variable TYPE?

Asked

Viewed 59 times

0

Follow two codes.

  • The first makes the desired operation with if and else.
  • The second (which I am doubtful about) I try to recognize the char typed as an operator to perform the operation.
#include <stdio.h>

main(){
    char operador = ' ';
    float valor1, valor2;
    printf("Entre com um tipo de operacao a ser realizada (+,-,*,/),o primeiro valor e o segundo valor\n");
    scanf("%c %f %f", &operador, &valor1, &valor2);
        if (operador == '+'){
        printf("Resultado da soma %.2f", valor1+valor2);
    }
        else if (operador =='-'){
        printf("Resultado da subtracao %.2f", valor1-valor2);
    }
        else if (operador =='*'){
        printf("Resultado da multiplicacao %.2f", valor1*valor2);
    }
        else{
        printf("Resultado da divisao %.2f", valor1/valor2);
    }

    printf("\n\n");
    system ("pause");
}

#include <stdio.h>
main(){
    char operador = ' ';
    float x, y,op,operacao;
    //op=operador
    printf("Entre com um tipo de operacao a ser realizada (+,-,*,/),o primeiro valor e o segundo valor\n");
    scanf("%c %f %f", &op, &x, &y);
    operação= x 'CHAR' y;
}

1 answer

0


Apparently there’s no way to do what you want in C, as noted in the answers here. You can do it:

#include <stdio.h>

int main(){
    char op;
    float x, y;
    //op=operador
    printf("Entre com um tipo de operacao a ser realizada (+,-,*,/),o primeiro valor e o segundo valor\n");
    scanf("%c %f %f", &op, &x, &y);
    float opc = (op=='+')?(x+y):((op=='-')?(x-y):((op=='*')?(x*y):0));
    printf("%f\n", opc);
}

The explanation of the code snippet is also in the link above.

  • I imagined making the compile, recognize that it is an operator, but Tabom valeuu

Browser other questions tagged

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