欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

php写简单计算器

程序员文章站 2024-02-27 12:36:33
...

php写简单计算器

<?php
echo <<<'FORM'
<form action="" method="post">
<input type="text" name="num1"/> 
<select name="oper">
<option value="+">+</option>
<option value="-">-</option>
<option value="*">*</option>
<option value="/">/</option>
<option value="%">%</option>
</select>
<input type="text" name="num2"/>
<input type="submit" value="计算" />
</form>
FORM;
$a = (bool)$_POST['num1'];//判断是否为空,这里不能用isset
$b = (bool)$_POST['num2'];
$num1 = $_POST['num1'];   //赋值
$num2 = $_POST['num2'];
$oper = $_POST['oper'];
$yan = is_numeric($_POST['num1']);//判断是否位数字
$zheng = is_numeric($_POST['num2']);
if($a&&$b ==true){ //是否为空
    if($yan&&$zheng ==true){   //是否为数字
        $dear = 0;
        switch($oper){         //计算
            case '+':
                $dear = $num1+$num2;
                break;
            case '-':
                $dear = $num1-$num2;
                break;
            case '*':
                $dear = $num1*$num2;
                break;
            case '/':
                $dear = $num1/$num2;
                break;
            case '%':
                $dear = $num1%$num2;
                break;
            default:
                echo '这个'.$oper.'不存在';

        }
        echo $num1.$oper.$num2.'='.$dear;
    }else{
        echo $num1.'或者'.$num2.'不是数字,请填写数字';
    }
}else{
    echo '<h2>不能为空</h2>';
}

功能一样

<!DOCTYPE html>
<html>
<head>
	<title></title>
</head>
<body>
	<form action="" method="post">
		<input type="text" name="num1" value="<?php echo $_POST['num1']?>" /> 
		<select name="oper">
			<option value="+">+</option>
			<option value="-">-</option>
			<option value="*">*</option>
			<option value="/">/</option>
			<option value="%">%</option>
		</select>
		<input type="text" name="num2" value="<?php echo $_POST['num2']?>" />
		<input type="submit" value="计算" />
	</form>

</body>
<?php   
if(((bool)$_POST['num1'])&&((bool)$_POST['num2']) ==true){ //是否为空
    if((is_numeric($_POST['num1']))&&(is_numeric($_POST['num2'])) ==true){   //是否为数字
        $dear = 0;
        switch($_POST['oper']){         //计算
            case '+':
                $dear = $_POST['num1']+$_POST['num2'];
                break;
            case '-':
                $dear = $_POST['num1']-$_POST['num2'];
                break;
            case '*':
                $dear = $_POST['num1']*$_POST['num2'];
                break;
            case '/':
                $dear = $_POST['num1']/$_POST['num2'];
                break;
            case '%':
                $dear = $_POST['num1']%$_POST['num2'];
                break;
            default:
                echo '这个'.$_POST['oper'].'不存在';

        }
        echo $_POST['num1'].$_POST['oper'].$_POST['num2'].'='.$dear;
    }else{
        echo $_POST['num1'].'或者'.$_POST['num2'].'不是数字,请填写数字';
    }
}else{
    echo '<h2>不能为空</h2>';
}
?>
</html>
相关标签: php