fork(1) download
  1. #include <stdio.h>
  2. #include <math.h>
  3. #include <string.h>
  4.  
  5. double nextval() {
  6. static double val;
  7. scanf("%lf", &val);
  8. return val;
  9. }
  10.  
  11. char nextop() {
  12. static char op[2] = "";
  13. if(scanf("%1s", op) < 1) // 입력의 끝?
  14. return '\0';
  15. return *op; // 연산자 리턴
  16. }
  17.  
  18. double do_calculate(double val1, char op, double val2) {
  19. switch(op) {
  20. case '+':
  21. return val1 + val2;
  22. case '-':
  23. return val1 - val2;
  24. case '*':
  25. return val1 * val2;
  26. case '/':
  27. return val1 / val2;
  28. case '^':
  29. return pow(val1, val2);
  30. case '<':
  31. return (double)((int)val1 * (1 << (int)val2));
  32. case '>':
  33. return (double)((int)val1 / (1 << (int)val2));
  34. case '&':
  35. return (double)((int)val1 & (int)val2);
  36. case '|':
  37. return (double)((int)val1 | (int)val2);
  38. }
  39. }
  40.  
  41. int check_later_is_prior(char op_first, char op_later) {
  42. const char *order = "^*+<&|";
  43.  
  44. if(op_first == '-') op_first = '+';
  45. else if(op_first == '/') op_first = '*';
  46. else if(op_first == '>') op_first = '<';
  47.  
  48. if(op_later == '-') op_later = '+';
  49. else if(op_later == '/') op_later = '*';
  50. else if(op_later == '>') op_later = '<';
  51.  
  52. return strchr(order, op_later) < strchr(order, op_first);
  53. }
  54.  
  55. double calculate(double val1, double op, double val2, char op2) {
  56. if(op2 == '\0') { // 연산이 더 없는 경우
  57. return do_calculate(val1, op, val2);
  58. } else {
  59. double nval = nextval();
  60. char nop = nextop();
  61.  
  62. if(check_later_is_prior(op, op2)) // 뒤의 연산을 더 먼저 해야하는 경우
  63. return do_calculate(val1, op, calculate(val2, op2, nval, nop));
  64. else
  65. return calculate(do_calculate(val1, op, val2), op2, nval, nop);
  66. }
  67. }
  68.  
  69. int main() {
  70. double val1 = nextval();
  71. char op1 = nextop();
  72. double val2 = nextval();
  73. char op2 = nextop();
  74. printf("Result: %g\n", calculate(val1, op1, val2, op2));
  75. return 0;
  76. }
Success #stdin #stdout 0s 3144KB
stdin
10 * 2^10
stdout
Result: 10240