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