# Skenz - How To Wiki

### Site Tools

cs:c_language:calc

# Differences

This shows you the differences between two versions of the page.

 cs:c_language:calc [2019/02/26 14:35] cs:c_language:calc [2019/02/26 14:35] (current) Line 1: Line 1: + ====== Calculator ====== + **Concepts:​**\\ + ''​switch''​ statement + + **Text:**\\ + Realize a C program that: + * By using the ''​switch''​ statement, implements a simple calculator + * The program receives as input two float numbers (i.e., the //​operands//​) and a character (i.e., the mathematical operator) + * The calculator must executed the operation expressed by the //​operator//​ and print the result of the operation + * Allowed operators are ''​+'',​ ''​-'',​ ''​*''​ and ''/''​. + * Finally, the program must signal an error in the case an incorrect operator is inserted by the user. + + **Example**:​\\ + <​code>​ + 3+9 + RESULT: 3.000000 + 9.000000 = 12.000000 + + 3^9 + ERROR: operator '​^'​ not recognized + ​ + + **Solution:​**\\ + + + #include <​stdio.h>​ + + int main() { + + float op1, op2, ris; + char oper; + int operator_is_recognized = 1; + + scanf("​%f %c %f", &op1, &oper, &op2); + + switch(oper) { + case '​+':​ + ris = op1 + op2; + break; + case '​-':​ + ris = op1 - op2; + break; + case '​*':​ + ris = op1 * op2; + break; + case '/':​ + ris = op1 / op2; + break; + default: + operator_is_recognized = 0; + } + + if (operator_is_recognized) + printf("​RESULT:​ %f %c %f = %f\n", op1, oper, op2, ris); + else + printf("​ERROR:​ operator '​%c'​ not recognized\n",​ oper); + + return 0; + } +