11

Calculator with 5 operations

  1. #include <stdio.h>
  2.  
  3. main() {
  4.     int x, y, r;
  5.     char op;
  6.  
  7.     printf( "Enter an operation (x [+-*/%%] y): " );
  8.  
  9.     if ( scanf("%d %c %d", &x, &op, &y ) == 3 ) {
  10.         switch ( op ) {
  11.             case '+':
  12.                 r = x + y;
  13.                 break;
  14.             case '-':
  15.                 r = x - y;
  16.                 break;
  17.             case '*':
  18.                 r = x * y;
  19.                 break;
  20.             case '/':
  21.                 if ( y == 0 )
  22.                     goto error;
  23.                 r = x / y;
  24.                 break;
  25.             case '%':
  26.                 if ( y == 0 )
  27.                     goto error;
  28.                 r = x % y;
  29.                 break;
  30.             default:
  31.                 goto error;
  32.         }
  33.         printf("%d %c %d = %d\n", x, op, y, r);
  34.     }
  35.     else
  36. error:
  37.         printf("What?\n");
  38. }
$ gcc -o calc calc.c
$ ./calc 
Enter an operation (x [+-*/%] y): 2 + 3
2 + 3 = 5
$ ./calc 
Enter an operation (x [+-*/%] y): 2 - 3
2 - 3 = -1
$ ./calc
Enter an operation (x [+-*/%] y): -2 * -3
-2 * -3 = 6
$ ./calc
Enter an operation (x [+-*/%] y): 2/3  
2 / 3 = 0
$ ./calc
Enter an operation (x [+-*/%] y): -2 % 3  
-2 % 3 = -2
$ ./calc
Enter an operation (x [+-*/%] y): 1.5 * 2
What?

Comments

Your comment:
[p] [b] [i] [u] [s] [quote] [pre] [br] [code] [url] [email] strip help 2000

Enter a maximum of 2000 characters.
Improve the presentation of your text with the following formatting tags:
[p]paragraph[/p], [b]bold[/b], [i]italics[/i], [u]underline[/u], [s]strike[/s], [quote]citation[/quote], [pre]as is[/pre], [br]line break,
[url]http://www.izend.org[/url], [url=http://www.izend.org]site[/url], [email]izend@izend.org[/email], [email=izend@izend.org]izend[/email],
[code]command[/code], [code=language]source code in c, java, php, html, javascript, xml, css, sql, bash, dos, make, etc.[/code].