标签:
#include <stdio.h> #include <stdlib.h> typedef enum { FALSE = 0, TRUE }BOOL; void calculator(void); int main(void) { char y = ‘ ‘; y = ‘y‘; while(‘y‘ == y) { printf("start calculator:\n"); calculator(); printf("restart?,printf ‘y‘ to continue\n"); scanf(" %c",&y); printf("%c\n",y); } return 0; } void calculator(void) { char c; char ucOperator = ‘ ‘; int k = 1; int value = 0; int lastValue = 0; int result = 0; int lastk; printf("start calculator input:\n"); /* while((c = getchar()) == ‘\n‘||c == ‘ ‘) { ; } //this does work,the below way is more simple */ scanf(" %c",&c); //filter space and return do{ if(c >= ‘0‘ && c <= ‘9‘) { if(!value) { value = c - ‘0‘; } else { value = value*10 + c- ‘0‘; } continue; } if(‘+‘ == c) { lastk = k; k = 1; } else { if(‘-‘ == c) { lastk = k; k = -1; c = ‘+‘; } } switch(c) { case ‘+‘: switch(ucOperator) { case ‘*‘: result += lastValue * value * lastk; break; case ‘/‘: result += lastValue / value * lastk; break; case ‘+‘: result += value * lastk; break; case ‘ ‘: result += value; break; default: break; } ucOperator = ‘+‘; break; case ‘*‘: lastValue = value; ucOperator = ‘*‘; break; case ‘/‘: lastValue = value; ucOperator = ‘/‘; break; case ‘=‘: if(‘+‘ == ucOperator) { result += value * k; } if(‘*‘ == ucOperator) { result += value * lastValue * k; } if(‘/‘ == ucOperator) { result += lastValue / value * k; } printf("%d\n",result); result = 0; ucOperator = ‘ ‘; break; default: break; } value = 0; }while((c = getchar()) != ‘\n‘); }
标签:
原文地址:http://www.cnblogs.com/aprilapril/p/5399498.html