0
The following code uses the decision structure to choose the command consistent with the operation chosen by the user.
How could I simplify that? I tried to modularize instruction printf
but I couldn’t.
#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");
}
How it would look Modularized?
printf("Digite um tipo de operacao(+,-,*,/) e em seguida o primeiro valor e o segundo valor\n");
scanf("%c %d %d", &o, &x, &y);
if(o=='+'){
op=x+y;
}
else if (o=='-'){
op=x-y;
}
else if (o=='*'){
op=x*y;
}
else{
op=x/y;
}
if(op==x+y && op==x-y && op==x*y && op==x/y){
printf("O resultado e:%d",op );
In my opinion, it’s simple enough and doesn’t need to change. Of course, someone might even suggest complicated things, like creating a mapping of operations -> function/message, or saying that "better use a
switch
" (it is not), but all this is wanting to complicate by chance, it does not need it. By the way, why do you think it is complicated?– hkotsubo
I didn’t want to have to repeat that much printf for each decision. I’m testing ideas and mine was modulating it. I’d look like this but it’s not working...
– David Faria
https://ideone.com/UZKqP7
– hkotsubo
I asked the question as if
– David Faria
Really complicated in this case, but thank you for illuminating my idea! KKK
– David Faria