您的位置:首页 > 编程语言 > PHP开发

PHP版计算器

2015-08-30 16:56 543 查看
</pre><pre name="code" class="php"><?php
/**
* Created by PhpStorm.
* User: Super pan
* Date: 2015/8/26
* Time: 19:47
*/

class CalController{

/**
* @return string
*/
public function showAnswer(){
$expression = $_GET['str'];
$exp= $this->arrange(str_split($expression));
$result= $this->getResult($exp);

$arr = array(
"expression"=>$expression,
"myanswer" => $result
);
return $this->array2Json($arr);
}

public function array2Json($arr) {

foreach ( $arr as $key => $value ) {
$arr[$key] = urlencode ($value);
}
$res = urldecode (json_encode ($arr));

return $res;
}

public function getResult($exp){
$result= array();

for($i=0; $i< count($exp); $i++){
if($this->isNum($exp[$i])){                                         //如果是数字
$result[]= $exp[$i];
}else if($exp[$i]!= '('){                                               //如果是运算符,且不是左括号 '('

$rank=$this->getRank($exp[$i]);
for($j=count($result)-1; $j>0; $j--){
$d=$result[$j];

if(!$this->isNum($d) && $this->getRank($d)>=$rank){         //该字符是运算符且优先级更大或相等
$r=$this->calc($result[$j-1],$result[$j+1], $result[$j]);
if($r=="by zero"){
return $r;
}
array_splice($result, $j+1, 1);
array_splice($result, $j, 1);
array_splice($result, $j-1, 1, $r);
}
}
$result[]= $exp[$i];

}else if($exp[$i]== '('){                                           //如果是左括号
$inner= array();
for($i=$i+1; $i<count($exp)&&$exp[$i]!=')'; $i++){
$inner[]= $exp[$i];
}
$innerResult= $this->getResult($inner);
if($innerResult=="by zero"){
return $innerResult;
}
$result[]= $innerResult;
}
}

$m=count($result)-1;
if($m!=0){
for( ; $m>0; $m--){
if(!$this->isNum($result[$m])){
$r=$this->calc($result[$m-1], $result[$m+1], $result[$m]);
array_splice($result, $m+1, 1);
array_splice($result, $m, 1);
array_splice($result, $m-1, 1, $r);
}
}
}

return $result[0];
}

public function arrange($array){                         //将形如'1','2','+','3','4'解析成'12','+','34'
$exp= array();

for($i=0; $i<count($array); $i++){

if(!is_numeric($array[$i])&&$array[$i]!='.'){
$exp[]= $array[$i];
}else{
$temp= '';
while($i<count($array)&&(is_numeric($array[$i])||$array[$i]=='.')){
$temp=$temp.$array[$i];
$i++;
}
$i--;
$exp[]=$temp;
}
}
return $exp;
}

public function getRank($d){
if($d=='+'||$d=='-'){                            //加减号优先级为1
return 1;
}else{                                           //乘除号优先级为2
return 2;
}
}

public function isNum($d){
if($d=='+'||$d=='-'||$d=='*'||$d=='/'||$d=='('||$d==')'){
return false;
}else{
return true;
}
}

public function calc($left, $right, $op){
if($op=='+')
return ($left+$right);
else if($op=='-')
return ($left-$right);
else if($op=='*'){
if($right=='0'){
return "by zero";
}else{
return ($left/$right);
}
}
else
return ($left/$right);
}

}

$p= new CalController();

$ans= $p->showAnswer();

echo $ans;
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: