fork download
  1. %{
  2. #undef yywrap
  3. #define yywrap() 1
  4. #include <math.h>
  5. #include <stdio.h>
  6. #include <stdlib.h>
  7.  
  8. int f1 = 0, f2 = 0;
  9. char oper;
  10. float op1 = 0, op2 = 0, ans = 0;
  11.  
  12. void eval();
  13. float deg_to_rad(float degrees); // Function to convert degrees to radians
  14. %}
  15.  
  16. DIGIT [0-9]
  17. NUM {DIGIT}+(\.{DIGIT}+)?
  18. OP [*/+\-]
  19.  
  20. %%
  21.  
  22. {NUM} {
  23. if (f1 == 0) {
  24. op1 = atof(yytext);
  25. f1 = 1;
  26. } else if (f2 == -1) {
  27. op2 = atof(yytext);
  28. f2 = 1;
  29. }
  30.  
  31. if (f1 == 1 && f2 == 1) {
  32. eval();
  33. f1 = 0;
  34. f2 = 0;
  35. }
  36. }
  37.  
  38. {OP} {
  39. oper = (char)*yytext;
  40. f2 = -1;
  41. }
  42.  
  43. [sS][il][nN]|[cC][oO][sS]|[tT][aA][nN] {
  44. oper = *yytext; // Correctly assigns the operation based on the first character
  45. f2 = -1;
  46. }
  47.  
  48. [0-9](\.[0-9]+)?[lL][oO][gG] {
  49. oper = 'l'; // Recognizes log as a valid operation
  50. f2 = -1;
  51. }
  52.  
  53. \n {
  54. if (f1 == 1 && f2 == 1) {
  55. eval();
  56. f1 = 0;
  57. f2 = 0;
  58. }
  59. }
  60.  
  61. %%
  62.  
  63. int main() {
  64. yylex();
  65. return 0;
  66. }
  67.  
  68. float deg_to_rad(float degrees) {
  69. return degrees * (M_PI / 180.0); // Convert degrees to radians
  70. }
  71.  
  72. void eval() {
  73. switch (oper) {
  74. case '+':
  75. ans = op1 + op2;
  76. break;
  77. case '-':
  78. ans = op1 - op2;
  79. break;
  80. case '*':
  81. ans = op1 * op2;
  82. break;
  83. case '/':
  84. if (op2 == 0) {
  85. printf("ERROR: Division by zero\n");
  86. return;
  87. } else {
  88. ans = op1 / op2;
  89. }
  90. break;
  91. case 's': // sin
  92. case 'S':
  93. ans = sin(deg_to_rad(op1)); // Convert input to radians
  94. break;
  95. case 'c': // cos
  96. case 'C':
  97. ans = cos(deg_to_rad(op1)); // Convert input to radians
  98. break;
  99. case 't': // tan
  100. case 'T':
  101. ans = tan(deg_to_rad(op1)); // Convert input to radians
  102. break;
  103. case 'l': // log
  104. case 'L':
  105. ans = log(op1);
  106. break;
  107. default:
  108. printf("Operation not available\n");
  109. break;
  110. }
  111. printf("The answer is = %f\n", ans);
  112. }
Success #stdin #stdout #stderr 0.02s 6900KB
stdin
Standard input is empty
stdout
Standard output is empty
stderr
ERROR: /home/KzgJFF/prog:112:0: Syntax error: Unexpected end of file
ERROR: '$runtoplevel'/0: Undefined procedure: program/0
   Exception: (3) program ? EOF: exit