c
#include <stdio.h> #include <string.h> #define BUFSIZE 1000 void main(void) { char* egets(char* buf, int size); int end_check(char* str); int cal_center(char command, double op1, double op2, double* anser); char input_buf[BUFSIZE]; char* buf; char command[] = "\0"; double op1, op2; int n; printf("\n\tcommand:\n\t -binary operator '+', '-', '*', '/', '%%'\n\t - exit 'q', 'e'\n\n"); for(;;) { if(cal_center(command[0], op1, op2, &op1)) { printf(" > %.0f ", op1); if(op1 == 0) printf("\n > "); } else { op1 = ( double )0; printf(" > "); } command[0] = '\0'; op2 = ( double )0; n = 0; if(end_check(buf = egets(input_buf, BUFSIZE))) break; if(op1 == 0) sscanf(buf, "%lf%n", &op1, &n); sscanf(buf += n, "%1s%n", command, &n); sscanf(buf += n, "%lf", &op2); } } char* egets(char* buf, int size) { int i, len; for(i = 0; i < size; i++) buf[i] = '\0'; fgets(buf, size, stdin); len = strlen(buf); if(buf[len-1] == '\n') buf[len-1] = '\0'; return( buf ); } int end_check(char* str) { int i; for(i = 0; str[i] != '\0'; i++) if(str[i] == 'e' || str[i] == 'E' || str[i] == 'q' || str[i] == 'Q') return( 1 ); return( 0 ); } int cal_center(char command, double op1, double op2, double* anser) { int sign = 1; switch(command) { case '+': *anser = op1 + op2; break; case '-': *anser = op1 - op2; break; case '*': *anser = op1 * op2; break; case '%': *anser = ( signed long int )op1 % ( signed long int )op2; break; case '/': if(op2 != 0) *anser = ( signed long int )(op1 / op2); else { printf(" error : zero divisor\n"); sign = 0; } break; case '\0': sign = 0; break; default: printf(" error : unknown command \"%c\"\n", command ); sign = 0; break; } return( sign ); }
command:
-binary operator '+', '-', '*', '/', '%'
- exit 'q', 'e'
> 10+2
> 12 *4
> 48 *-9
> -432 -3
> -435 /5
> -87 %8
> -7 /-1
> 7 -7
> 0
> 2+-3
> -1