fork(1) download
  1. <?php
  2.  
  3. $operator = array('+', '-', '*', '=', '/');
  4.  
  5. $input = '-2.43+3.62/2.1*9.02=';
  6. $inputLength = mb_strlen($input);
  7.  
  8. $numberText = '';
  9. $result = 0;
  10. $op = '';
  11.  
  12. for ($i = 0; $i < $inputLength; $i++) {
  13. $char = mb_substr($input, $i, 1);
  14.  
  15. if (in_array($char, $operator)) {
  16. if ($char == '=') {
  17. switch ($op) {
  18. case '+':
  19. $result += floatval($numberText);
  20. break;
  21. case '-':
  22. $result -= floatval($numberText);
  23. break;
  24. case '*':
  25. $result *= floatval($numberText);
  26. break;
  27. case '/':
  28. $result /= floatval($numberText);
  29. break;
  30. }
  31. } else {
  32. switch ($op) {
  33. case '':
  34. $result = floatval($numberText);
  35. break;
  36. case '+':
  37. $result += floatval($numberText);
  38. break;
  39. case '-':
  40. $result -= floatval($numberText);
  41. break;
  42. case '*':
  43. $result *= floatval($numberText);
  44. break;
  45. case '/':
  46. $result /= floatval($numberText);
  47. break;
  48. }
  49. }
  50. echo "op = [$op], number = [$numberText], result = [$result], char = [$char]\n";
  51. $numberText = '';
  52. $op = $char;
  53. } elseif (is_numeric($char) || $char == '.') {
  54. $numberText .= $char;
  55. } else {
  56. echo "Непонятный символ. Работа программы прекращена\n";
  57. exit();
  58. }
  59. }
  60.  
  61. echo "{$input}{$result}";
Success #stdin #stdout 0s 52488KB
stdin
Standard input is empty
stdout
op = [], number = [], result = [0], char = [-]
op = [-], number = [2.43], result = [-2.43], char = [+]
op = [+], number = [3.62], result = [1.19], char = [/]
op = [/], number = [2.1], result = [0.56666666666667], char = [*]
op = [*], number = [9.02], result = [5.1113333333333], char = [=]
-2.43+3.62/2.1*9.02=5.1113333333333