14

Calculette à 5 opérations

  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?

Commentaires

Votre commentaire :
[p] [b] [i] [u] [s] [quote] [pre] [br] [code] [url] [email] strip aide 2000

Entrez un maximum de 2000 caractères.
Améliorez la présentation de votre texte avec les balises de formatage suivantes :
[p]paragraphe[/p], [b]gras[/b], [i]italique[/i], [u]souligné[/u], [s]barré[/s], [quote]citation[/quote], [pre]tel quel[/pre], [br]à la ligne,
[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]commande[/code], [code=langage]code source en c, java, php, html, javascript, xml, css, sql, bash, dos, make, etc.[/code].