繁星coding
2018-06-05 11:49:08浏览 4414
<html>
<head>
<title>PHP简单计算器</title>
<meta http-equiv="Content-Type" content="text/html;charset=utf-8" />
<style>
table{
border:1px solid #CC9999;
width:600px;
}
th{
background:#CCCCCC;
}
td{
background:#CCC;
font:Georgia, "Times New Roman", Times, serif;
}
.setno{
color:#FF0000;
}
.setyes{
color:#03F;
}
</style>
</head>
<body>
<?php
$num1 = true; //判断第一个数是否为空
$num2 = true; //判断第二个数是否为空
$iszeno = true;//判断除数是否为0
$isnum1 = true; //判断第一个数是否为有效数
$isnum2 = true;//判断第二个数是否为有效数
$message = ""; //记录错误消息
if(isset($_POST["js"])){
if($_POST["num1"] == ""){
$num1 = false;
$message .= "第一个数不能为0!";
}
if($_POST["num2"] == ""){
$num2 = false;
$message .= "第二个数不能为0!";
}else{
if( $_POST["opt"] == "/" && $_POST["num2"] == "0"){
$iszeno = false;
$message .= "除数不能为0!";
}
if($_POST["opt"] == "%" && $_POST["num2"] == "0"){
$iszeno = false;
$message .= "除数不能为0!";
}
}
if(!is_numeric($_POST["num1"])){
$isnum1 = false;
$message .= "第一个数不是有效数,请输入一个有效数字!";
}
if(!is_numeric($_POST["num2"])){
$isnum2 = false;
$message .= "第二个数不是有效数,请输入一个有效数字!";
}
}
/* */
?>
<table align="center">
<form action="jsq.php" method="post">
<caption><h1>计算器 <SUB>----by Jackie Lee</SUB></h1></caption>
<tr>
<th>
<input type="text" size="4" name="num1" value = "<?php echo $_POST["num1"]?>"/>
</th>
<th>
<select name="opt">
<option value="+" <?php echo $_POST["opt"] == "+"?"selected":""?>>+</option>
<option value="-" <?php echo $_POST["opt"] == "-"?"selected":""?>>-</option>
<option value="*" <?php echo $_POST["opt"] == "*"?"selected":""?>>*</option>
<option value="/" <?php echo $_POST["opt"] == "/"?"selected":""?>>/</option>
<option value="%" <?php echo $_POST["opt"] == "%"?"selected":""?>>%</option>
</select>
</th>
<th>
<input type="text" size="4" name="num2" value = "<?php echo $_POST["num2"]?>" />
</th>
<th>
<input type="submit" name="js" value="计算" />
</th>
</tr>
</form>
<?php
if(isset($_POST["js"])){
echo '<tr><td colspan="4">';
$result = 0.0;
switch($_POST["opt"]){
case '+':
$result = $_POST["num1"] + $_POST["num2"];
break;
case '-':
$result = $_POST["num1"] - $_POST["num2"];
break;
case '*':
$result = $_POST["num1"] * $_POST["num2"];
break;
case '/':
if($_POST["num2"] != "0"){
$result = $_POST["num1"] / $_POST["num2"];
}
break;
case '%':
if($_POST["num2"] != "0"){
$result = $_POST["num1"] % $_POST["num2"];
}
break;
}
if(!$message){
echo '<font class="setyes">'."计算结果:".$_POST["num1"]." ".$_POST["opt"]." ".$_POST["num2"]." = ".$result."</font>";
}else{
echo '错误:<font class="setno">'.$message."</font>";
}
echo '</td></tr>';
}
?>
</table>
</body>
</html>