User Tools

Site Tools


cs:c_language:calc
Return to Home page

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:

3+9
RESULT: 3.000000 + 9.000000 = 12.000000

3^9
ERROR: operator '^' not recognized

Solution:

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;
}

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

You can reuse, distribute or modify the content of this page, but you must cite in any document (or webpage) this url: http://wiki.altervista.org/cs/c_language/calc
/membri/wiki/data/pages/cs/c_language/calc.txt · Last modified: 2015/10/28 15:22 (external edit)


Policy sui Cookie