<body> <table align="center" border=1 width=500> <h2 align="center">计算器</h2> <form action="jisuanqi.php" mothed="GET"> <tr> <td> <input type="text" name="num1" /> </td> <td> <select name="ysf"> <option value="+">+</option> <option value="-">-</option> <option value="×">×</option> <option value="÷">÷</option> </select> </td> <td> <input type="text" name="num2" /> </td> <td> <input type="submit" name="sub" value="提交" /> </td> </tr> </form> </table> </body> <?php if(isset($_GET["sub"])){ $num1=$_GET["num1"]; //被除数 $num2=$_GET["num2"]; //除数 $ysf=$_GET["ysf"]; //运算符 $error=""; //错误信息 //检查各个参数是否正确 if($num1=="" || $num2==""){ $error="缺失参数!"; }elseif(!is_numeric($num1) || !is_numeric($num2)){ $error="参数错误!"; }else{ //选择不同的运算操作 switch($ysf){ case "+": $result=$num1+$num2; break; case "-": $result=$num1-$num2; break; case "×": $result=$num1*$num2; break; case "÷": if($num2=="0") $error="零不能作为除数"; else $result=$num1/$num2; break; } } //输出结果 echo "<table align='center' border=1 width=500><tr><td>"; if($error <> "") echo $error; else echo "结果:".$num1.$ysf.$num2."=".$result; echo "</td></tr></table>"; } ?> </body>
此代码计算后,原位置不能显示输入的计算数值
优化后代码
<body> <table align="center" border=1 width=500> <h2 align="center">计算器</h2> <form action="jisuanqi.php" mothed="GET"> <tr> <td> <input type="text" name="num1" value="<?php echo isset($_GET['num1']) && !empty($_GET['num1']) ? $_GET['num1'] : ''?>"/> </td> <td> <select name="ysf"> <option value="+" <?php if(isset($_GET[ "ysf"]) && $_GET[ "ysf"]=="+" ){echo 'selected="selected"';} ?>>+</option> <option value="-" <?php if(isset($_GET[ "ysf"]) && $_GET[ 'ysf']=='-' ){echo 'selected="selected"';} ?>>-</option> <option value="×" <?php if(isset($_GET[ "ysf"]) && $_GET[ 'ysf']=='×' ){echo 'selected="selected"';} ?>>×</option> <option value="÷" <?php if(isset($_GET[ "ysf"]) && $_GET[ 'ysf']=='÷' ){echo 'selected="selected"';} ?>>÷</option> </select> </td> <td> <input type="text" name="num2" value="<?php echo isset($_GET['num2']) && !empty($_GET['num2']) ? $_GET['num2'] : ''?>"/> </td> <td> <input type="submit" name="sub" value="提交"/> </td> </tr> </form> </table> <?php if ( isset( $_GET[ "sub" ] ) ) { $num1 = $_GET[ "num1" ]; //被除数 $num2 = $_GET[ "num2" ]; //除数 $ysf = $_GET[ "ysf" ]; //运算符 $error = ""; //错误信息 //检查各个参数是否正确 if ( $num1 == "" || $num2 == "" ) { $error = "缺失参数!"; } elseif ( !is_numeric( $num1 ) || !is_numeric( $num2 ) ) { $error = "参数错误!"; } else { //选择不同的运算操作 switch ( $ysf ) { case "+": $result = $num1 + $num2; break; case "-": $result = $num1 - $num2; break; case "×": $result = $num1 * $num2; break; case "÷": if ( $num2 == "0" ) $error = "零不能作为除数"; else $result = $num1 / $num2; break; } } //输出结果 echo "<table align='center' border=1 width=500><tr><td>"; if ( $error <> "" ) echo $error; else echo "结果:" . $result; echo "</td></tr></table>"; } ?> </body>