Introduction: This is a detailed page for calculating the four arithmetic expressions implemented by PHP. It introduces PHP, related knowledge, skills, experience, and some PHP source code.
Class = 'pingjiaf' frameborder = '0' src = 'HTTP: // biancheng.dnbc?info/pingjia.php? Id = 342053 'rolling = 'no'>
Requirement: There is a string expression for four arithmetic operations. Compile a function to calculate the results of the four arithmetic operations.
PHP implementation:
1 <? PHP
2
3 /**
4 * calculate four arithmetic expressions
5 */
6
7 error_reporting (e_all );
8
9 $ exp = '(1 + 2*(3 + 5)/4) * (3 + (5-4) * 2 )';
10 $ arr_exp = array ();
11
12 For ($ I = 0; $ I <strlen ($ exp); $ I ++ ){
13 $ arr_exp [] = $ exp [$ I];
14}
15 $ result = calcexp (array_reverse ($ arr_exp ));
16 echo $ exp. '='. $ result;
17
18 function calcexp ($ exp ){
19 $ arr_n = array ();
20 $ arr_op = array ();
21
22 while ($ S = array_pop ($ exp ))! = ''){
23 if ($ S = '('){
24 $ temp = array (); $ quote = 1; $ endquote = 0;
25 while ($ T = array_pop ($ exp ))! = ''){
26 if ($ T = '('){
27 $ quote ++;
28}
29 if ($ T = ')'){
30 $ endquote ++;
31 if ($ quote ==$ endquote ){
32 break;
33}
34}
35 array_push ($ temp, $ t );
36}
37 $ temp = array_reverse ($ temp );
38 array_push ($ arr_n, calcexp ($ temp ));
39} else if ($ S = '*' | $ S = '/'){
40 $ n2 = array_pop ($ exp );
41 if ($ n2 = '('){
42 $ temp = array (); $ quote = 1; $ endquote = 0;
43 while ($ T = array_pop ($ exp ))! = ''){
44 if ($ T = '('){
45 $ quote ++;
46}
47 if ($ T = ')'){
48 $ endquote ++;
49 if ($ quote = $ endquote)
50 break;
51}
52 array_push ($ temp, $ t );
53}
54 $ temp = array_reverse ($ temp );
55 $ n2 = calcexp ($ temp );
56}
57
58 $ op = $ S;
59 $ n1 = array_pop ($ arr_n );
60
61 $ result = operation ($ N1, $ op, $ N2 );
62 array_push ($ arr_n, $ result );
63} elseif ($ S = '+' | $ S = '-'){
64 array_push ($ arr_op, $ S );
65} else {
66 array_push ($ arr_n, $ S );
67}
68}
69
70 $ n2 = array_pop ($ arr_n );
71 while ($ op = array_pop ($ arr_op ))! = ''){
72 $ n1 = array_pop ($ arr_n );
73 $ n2 = operation ($ N1, $ op, $ N2 );
74}
75
76 return $ N2;
77}
78
79 function operation ($ N1, $ op, $ N2 ){
80 switch ($ OP ){
81 Case '+ ':
82 return intval ($ N1) + intval ($ N2 );
83 break;
84 case '-':
85 return intval ($ N1)-intval ($ N2 );
86 break;
87 case '*':
88 return intval ($ N1) * intval ($ N2 );
89 break;
90 case '/':
91 return intval ($ N1)/intval ($ N2 );
92 break;
93}
94}
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, next I will add the "inverse polish expression"Algorithm.
Love J2EE follow Java Michael Jackson video station JSON online tools
Http://biancheng.dnbcw.info/php/342053.html pageno: 6.