<?php $input = '243+6743-78*2='; $number = 0; /*текущее число, которое набирает пользователь*/ $result = 0;/*Результат предыдущих действий*/ $op = ''; /*предыдущая операция(+-*)*/ for($i = 0; $i<$inputLength; $i++){ if($char == '+'||$char == '*'||$char == '-'||$char == '=' ){ if($char == '='){ switch($op){ case '+': $result = $result + $number; break; case '-': $result = $result - $number; break; case '*': $result = $result * $number; break; } echo "Ответ: $result\n"; } elseif($op == ''){ $op = $char; $result = $number; $number = 0; } elseif($op == '+'){ $result = $result + $number; $number = 0; $op = $char; } elseif($op == '-'){ $result = $result - $number;; $number = 0; $op = $char; } elseif($op = '*'){ $result = $result * $number; $number = 0; $op = $char; } } } else{ echo "Неверный символ: '$char'\n"; } echo "op=[$op], result=[$result], number=[$number], char=[$char]\n"; }
Standard input is empty
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