User Tools

Site Tools


cs:c_language:calc
Return to Home page

Differences

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

Link to this comparison view

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
 +</​code>​
 +
 +**Solution:​**\\
 +
 +<file C calc.c>
 +#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;
 +}
 +</​file>​
  

If you found any error, or if you want to partecipate to the editing of this wiki, please contact: admin [at] skenz.it

You can reuse, distribute or modify the content of this page, but you must cite in any document (or webpage) this url: https://www.skenz.it/cs/c_language/calc?rev=1551188114&do=diff
/web/htdocs/www.skenz.it/home/data/pages/cs/c_language/calc.txt ยท Last modified: 2019/02/26 14:35 (external edit)

Privacy Policy