<?php
//计算器处理的PHP代码
if(!empty($_POST['sub'])){
//echo "提交";
$err = "";
$flag = true;
if($_POST['num1'] == ""){
$flag = false;
$err .="第一个数不能为空<br>";
}else{
if(!is_numeric($_POST['num1'])){
$flag = false;
$err .="第一个不是数字,无法计算<br>";
}
}
if($_POST['num2'] == ""){
$flag = false;
$err .="第二个数不能为空";
}else{
if(!is_numeric($_POST['num2'])){
$flag = false;
$err .="第二个不是数字,无法计算<br>";
}
}
$sum = 0;
if($flag){
switch($_POST['ysf']){
case "+":
$sum = $_POST['num1'] + $_POST['num2'];
break;
case "-":
$sum = $_POST['num1'] - $_POST['num2'];
break;
case "x":
$sum = $_POST['num1'] * $_POST['num2'];
break;
case "/":
if($_POST['num2'] == 0){
$flag = false;
$err .= "除数不能为0";
break;
}else{
$sum = $_POST['num1'] / $_POST['num2'];
break;
}
case "%":
if($_POST['num2'] == 0){
$flag = false;
$err .= "除数不能为0";
break;
}else{
$sum = $_POST['num1'] % $_POST['num2'];
break;
}
}
}
}
?>
<html>
<head>
<title>简易计算器</title>
</head>
<body>
<table align="center" border=0 width="400">
<form action="<?php echo $_SERVER["PHP_SELF"]; ?>" method="post">
<caption><h1>一个简易计算器</h1></caption>
<tr>
<td>
<input type="text" name="num1" value="<?php echo $num1; ?>" size=5>
</td>
<td>
<select name="ysf">
<option name="+" <?php if($_POST['ysf'] == "+") echo "selected"; ?>>+</option>
<option name="-" <?php if($_POST['ysf'] == "-") echo "selected"; ?>>-</option>
<option name="x" <?php if($_POST['ysf'] == "x") echo "selected"; ?>>x</option>
<option name="/" <?php if($_POST['ysf'] == "/") echo "selected"; ?>>/</option>
<option name="%" <?php if($_POST['ysf'] == "%") echo "selected"; ?>>%</option>
</select>
</td>
<td>
<input type="text" name="num2" value="<?php echo $num2; ?>" size=5>
</td>
<td>
<input type="submit" name="sub" value="提交">
</td>
</tr>
<tr>
<td colspan="4">
<?php
if($flag){
echo "运算结果是:".$_POST['num1'].' '.$_POST['ysf'].' '.$_POST['num2'].' = '.$sum;
}else{
echo $err;
}
?>
</td>
</tr>
</form>
</table>
</body>
</html>
err以及flag变量均已在代码上部php代码中定义,但是运行时还是提示在html代码块中flag和err没有定义,请问这样改如何解决?另外就是提示变量num1和变量num2没有定义,这样的提示是否是需要$num1 = $_POST['num1']; 这样定义一下?
慕函数1130379