日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程语言 > php >内容正文

php

PHP计算表达式-栈

發布時間:2024/9/20 php 24 豆豆
生活随笔 收集整理的這篇文章主要介紹了 PHP计算表达式-栈 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
<?php /*** 計算表達式思路* 1+2*3-2* 思路:* 1、掃描每個字符* 2、判斷是否運算符和數字* 3、數字直接進棧* 4、運算符* 1、第一個運算符直接入棧* 2、N個運算符要與之前運算符比較* 1、如果當前運算符大于棧頂的運算符* 1、從數棧取出兩個數字進行運算,其實這個就是優先級運算* 2、把結果入棧* 2、如果不大于直接入棧* 5、得到平級運算表達式* 6、遍歷運算符出棧進行運算,然后在入棧,一直到運算符為空。* @author wangdk**/ class Expression {public $numArray = array();public $operArray = array();/*** 判斷是否為數字*/public function isNumeric($str) {return is_numeric($str);}/*** 判斷是否為運算符*/public function isOperation($str) {if ($str == '+' || $str == '-') {return 1;}if ($str == '*' || $str == '/') {return 2;}return 0;}/*** 根據運算符進行運算*/public function calc($ch, $numA, $numB) {$result = 0;switch($ch) {case '+':$result = $numA + $numB;break;case '-':$result = $numB - $numA;break;case '*':$result = $numA * $numB;break;case '/':$result = $numB / $numA;break;}return $result;}/*** 掃描表達式進行入棧*/public function getResult($str) {$count = strlen($str);for ($i = 0; $i < $count; $i++) {// 數字直接入棧if ($this->isNumeric($str[$i])) {array_push($this->numArray, $str[$i]);} else {// 第一個運算符直接入棧if (empty($this->operArray)) {$this->operArray[] = $str[$i];} else {// 多個運算符開始比較,去掉優先級$operArrayCopy = $this->operArray;$prev_operation = array_pop($operArrayCopy);// 如果當前運算符號小于 上一個運算符if ($this->isOperation($str[$i]) <= $this->isOperation($prev_operation)) {// 運算$prev_operation = array_pop($this->operArray);$first_num = array_pop($this->numArray);$second_num = array_pop($this->numArray);$result = $this->calc($prev_operation, $first_num, $second_num);$this->numArray[] = $result;array_push($this->operArray, $str[$i]);} else {array_push($this->operArray, $str[$i]);}}}}// 遍歷平級運算符,進行運算$operArrayCount = count($this->operArray);while($operArrayCount) {$prev_operation = array_pop($this->operArray);$first_num = array_pop($this->numArray);$second_num = array_pop($this->numArray);$result = $this->calc($prev_operation, $first_num, $second_num);$this->numArray[] = $result;$operArrayCount = count($this->operArray);}}}$e = new Expression(); $e->getResult('1+2*3+4*8'); echo '<pre>'; print_r($e->numArray); print_r($e->operArray) ?>

轉載于:https://my.oschina.net/wangdk/blog/158787

總結

以上是生活随笔為你收集整理的PHP计算表达式-栈的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。