php计算器怎么做
发布网友
发布时间:2022-04-29 15:35
我来回答
共2个回答
热心网友
时间:2022-05-10 15:11
<html>
<head>
<title>运算</title>
</head>
<body>
运算步骤:
<?php
$content=$_POST["content"];
if($content!=""){
run($content);
}
//去括号
function run($content){
$j=0;
for($i=0;$i<strlen($content);$i++){
if($content{$i}=="("){
$j=$i;
}
else if($content{$i}==")"){
$left=substr($content,0,$j);
$right=substr($content,$i+1,strlen($content)-$i);
$indexvalue=substr($content,$j+1,$i-$j-1);
getResult($indexvalue);
run($left.getValue().$right);
break;
}
if($i==strlen($content)-1){
getResult($content);
echo "<br>运算结果:".getValue();
break;
}
}
}
//运算
function getOne($one,$two,$char){
$result;
switch ($char) {
case "+":
$result=$one+$two;
break;
case "-":
$result=$one-$two;
break;
case "*":
$result=$one*$two;
break;
case "/":
$result=$one/$two;
break;
}print($one.$char.$two."=".$result." ");
return $result;
}
//递归运算
function getResult($content){
$j=0;//存储加减号位置
$array;//存储加减号
$char;//存储加减号位置
for($i=0;$i<strlen($content);$i++){
if($content{$i}=="+" || $content{$i}=="-" || $content{$i}=="*" || $content{$i}=="/" ){
if($i!=0){
$array[$j]=$i;
$char[$j]=$content{$i};
$j++;
}
}
}
if(count($char)==1){
$one=substr($content,0,$array[0]);
$two=substr($content,$array[0]+1,strlen($content)-$array[0]);
$result=getOne($one,$two,$char[0]);
setValue($result);
}else{
for($i=0;$i< count($char);$i++){
if($char[0]=="+" || $char[0]=="-"){
if($char[1]=="+" || $char[1]=="-"){
$one=substr($content,0,$array[0]);
$two=substr($content,$array[0]+1,$array[1]-$array[0]-1);
$result=getOne($one,$two,$char[0]);
$right=substr($content,$array[1],strlen($content)-$array[1]);
getResult($result.$right);
break;
}else if($char[1]=="*" || $char[1]=="/"){
$one=substr($content,$array[0]+1,$array[1]-$array[0]-1);
$left=substr($content,0,$array[0]+1);
if($char[2]==""){
$two=substr($content,$array[1]+1,strlen($content)-$array[1]);
$result=getOne($one,$two,$char[1]);
getResult($left.$result);
break;
}else{
$two=substr($content,$array[1]+1,$array[2]-$array[1]-1);
$result=getOne($one,$two,$char[1]);
$right=substr($content,$array[2],strlen($content)-$array[2]);
getResult($left.$result.$right);
break;
}
}
}else if($char[0]=="*" || $char[0]=="/"){
$one=substr($content,0,$array[0]);
$two=substr($content,$array[0]+1,$array[1]-$array[0]-1);
$result=getOne($one,$two,$char[0]);
$right=substr($content,$array[1],strlen($content)-$array[1]);
getResult($result.$right);
break;
}
}
}
}
$value;
//得到结果
function getValue(){
global $value;
return $value;
}
//存储结果
function setValue($value1){
global $value;
$value=$value1;
}
?>
<form action="999999999.php" method="post">
<?php
echo "<input type=text name=content value=".$content.">";
?>
<input type="submit" value=" 计 算 " >
</form>
</body>
</html>
热心网友
时间:2022-05-10 16:29
慕课网上有教程