15
Calculette à 5 opérations
- #include <stdio.h>
- main() {
- int x, y, r;
- char op;
- printf( "Enter an operation (x [+-*/%%] y): " );
- if ( scanf("%d %c %d", &x, &op, &y ) == 3 ) {
- switch ( op ) {
- case '+':
- r = x + y;
- break;
- case '-':
- r = x - y;
- break;
- case '*':
- r = x * y;
- break;
- case '/':
- if ( y == 0 )
- goto error;
- r = x / y;
- break;
- case '%':
- if ( y == 0 )
- goto error;
- r = x % y;
- break;
- default:
- goto error;
- }
- printf("%d %c %d = %d\n", x, op, y, r);
- }
- else
- error:
- printf("What?\n");
- }
$ 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