分享一个php简单的网页计算器,含有加减乘除
博主:紫藤心-迷途
浏览次数:1223次
今天整理了一个php简单的网页计算器,含有加减乘除,希望对刚学编程的你有所帮助!
前端提交的代码如下:
首先创建一个index.php文件
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>PHP版网页计算器</title> </head> <body style="text-align: center;"> <h2>网页计算器</h2> <form action="" method="post"> <input name="num1" type="text" id="num1" size="10" onkeyup="this.value=this.value.replace(/\D/g,'')" onafterpaste="this.value=this.value.replace(/\D/g,'')"/> <select name="oper" id="oper"> <option>+</option> <option>-</option> <option>*</option> <option>/</option> </select> <input name="num2" type="text" id="num2" size="10" onkeyup="this.value=this.value.replace(/\D/g,'')" onafterpaste="this.value=this.value.replace(/\D/g,'')"/> <input type="submit" name="Submit" value="计算" /> </form> <p></p> <?php error_reporting(0); $num1=$_POST["num1"]; $num2=$_POST["num2"]; $oper=$_POST["oper"]; require 'function.php';//引入方法 if($num1 !='' && $num2 !=''){ if($num2 == 0 && $oper=="/"){ $result=calc($num1,$num2,$oper); echo '计算的结果为:0'; }else{ $result=calc($num1,$num2,$oper); echo '计算的结果为:'.$result; } }else{ die('<font color="red">没有填写要计算的数字!</font>'); } ?> </body> </html>
表单文本框里面只能填写数字:onkeyup="this.value=this.value.replace(/\D/g,'')" onafterpaste="this.value=this.value.replace(/\D/g,'')"
其次创建一个function.php页面,用于处理加减乘除的计算:
代码如下:
<?php //计算加减乘除的方法 function calc($num1,$num2,$oper){ $result=0; switch($oper){ case "+": $result=$num1+$num2; break; case "-": $result=$num1-$num2; break; case "*": $result=$num1*$num2; break; case "/": $result=$num1/$num2; break; default: $result='请重新输入!'; break; } return $result; } ?>
下面我们来看看效果图:
就这样一个简单的php网页计算器就出来了!