Use four arithmetic expressions implemented by PHP to calculate the code. PHP implementation: Copy the code as follows :? Php *** calculates four arithmetic expressions * error_reporting (E_ALL); $ exp (1 + 2*(3 + 5) 4) * (3 + (5-4) * 2); $ arr_exparray (); for ($ i0; $ istrlen ($ PHP implementation:
The code is as follows:
/**
* Calculates four arithmetic expressions.
*/
Error_reporting (E_ALL );
$ Exp = '(1 + 2*(3 + 5)/4) * (3 + (5-4) * 2 )';
$ Arr_exp = array ();
For ($ I = 0; $ I $ Arr_exp [] = $ exp [$ I];
}
$ Result = calcexp (array_reverse ($ arr_exp ));
Echo $ exp. '='. $ result;
Function calcexp ($ exp ){
$ Arr_n = array ();
$ Arr_op = array ();
While ($ s = array_pop ($ exp ))! = ''){
If ($ s = '('){
$ Temp = array (); $ quote = 1; $ endquote = 0;
While ($ t = array_pop ($ exp ))! = ''){
If ($ t = '('){
$ Quote ++;
}
If ($ t = ')'){
$ Endquote ++;
If ($ quote = $ endquote ){
Break;
}
}
Array_push ($ temp, $ t );
}
$ Temp = array_reverse ($ temp );
Array_push ($ arr_n, calcexp ($ temp ));
} Else if ($ s = '*' | $ s = '/'){
$ N2 = array_pop ($ exp );
If ($ n2 = '('){
$ Temp = array (); $ quote = 1; $ endquote = 0;
While ($ t = array_pop ($ exp ))! = ''){
If ($ t = '('){
$ Quote ++;
}
If ($ t = ')'){
$ Endquote ++;
If ($ quote = $ endquote)
Break;
}
Array_push ($ temp, $ t );
}
$ Temp = array_reverse ($ temp );
$ N2 = calcexp ($ temp );
}
$ Op = $ s;
$ N1 = array_pop ($ arr_n );
$ Result = operation ($ n1, $ op, $ n2 );
Array_push ($ arr_n, $ result );
} Elseif ($ s = '+' | $ s = '-'){
Array_push ($ arr_op, $ s );
} Else {
Array_push ($ arr_n, $ s );
}
}
$ N2 = array_pop ($ arr_n );
While ($ op = array_pop ($ arr_op ))! = ''){
$ N1 = array_pop ($ arr_n );
$ N2 = operation ($ n1, $ op, $ n2 );
}
Return $ n2;
}
Function operation ($ n1, $ op, $ n2 ){
Switch ($ op ){
Case '+ ':
Return intval ($ n1) + intval ($ n2 );
Break;
Case '-':
Return intval ($ n1)-intval ($ n2 );
Break;
Case '*':
Return intval ($ n1) * intval ($ n2 );
Break;
Case '/':
Return intval ($ n1)/intval ($ n2 );
Break;
}
}
Two stacks are used in this implementation method. one is used to store numbers, and the other is used to store operators. when parentheses are encountered, they are recursively entered into the brackets for calculation. the implementation method is a bit clumsy, the following describes the implementation of the "inverse Polish expression" algorithm.
The pipeline code is as follows :? Php/*** calculates four arithmetic expressions */error_reporting (E_ALL); $ exp = '(1 + 2*(3 + 5)/4) * (3 + (5-4) * 2) '; $ arr_exp = array (); for ($ I = 0; $ istrlen ($...