PHP的基础计算器,PHP基础计算器

设计一个计算的功能,该功能能够完成运算并且能够对不合理的数据进行验证并且给出错误提示.
规则: 第一个数,第二个数不能够为空
如果操作符是/,第二个数数不能够为0.

1 php
2 header('Content-Type:text/html; charset=utf-8'
);
3 /*设计一个计算的功能,该功能能够完成运算并且能够对不合理的数据进行验证并且给出错误提示.
4 规则: 第一个数,第二个数不能够为空
5 如果操作符是/,第二个数数不能够为0.*/
6
7 function jsq(
$num1,
$oper,
$num2){
8 //检测数据不能为空并提示
9 if(!
isset(
$num1) || !
is_numeric(
$num1)){
10 $error = ERROR
11 <script>
<span>12 alert('第一个数不合法'<span>);
<span>13 </script>
14 ERROR;
15 return $error;
16 }
17 if(!
isset(
$num2) || !
is_numeric(
$num2)){
18 $error = ERROR
19 <script>
<span>20 alert('第二个数不合法'<span>);
<span>21 </script>
22 ERROR;
23 return $error;
24 }
25
26 if(
$oper == "+"
){
27 $result =
$num1 +
$num2;
28 }
elseif(
$oper == "-"
){
29 $result =
$num1 -
$num2;
30 }
elseif(
$oper == "*"
){
31 $result =
$num1 *
$num2;
32 }
elseif(
$oper = "/"
){
33 if(
$num2 == 0
){
34 $error = ERROR
35 <script>
<span>36 alert('第二个数不能为0'<span>);
<span>37 </script>
38 ERROR;
39 return $error;
40 }
41 $result =
$num1 /
$num2;
42 }
43 return $result;
44 }
45
46 if(
$_SERVER['REQUEST_METHOD'] == "POST"
){
47 $res = jsq(
$_POST['num1'],
$_POST['oper'],
$_POST['num2'
]);
48 }
49 ?>
50
51 用php写的基础计算器
52
64 计算结果为:echo
isset(
$res)?
$res:""; ?>
View Code
php获取一个表达式之后
对表达式分析处理。你可以看看数据结构的书。
如果只是做简单计算器的话,那就是获取两个数字一个操作符。那就更简单啦。
不知道你这个计算器要实现多少功能
根据你的代码,我实现了一下。
你可以试一试,有问题再追问。
表单数据传递 请在下面的表单中输入两数以求其值
Stellungnahme:Der Inhalt dieses Artikels wird freiwillig von Internetnutzern beigesteuert und das Urheberrecht liegt beim ursprünglichen Autor. Diese Website übernimmt keine entsprechende rechtliche Verantwortung. Wenn Sie Inhalte finden, bei denen der Verdacht eines Plagiats oder einer Rechtsverletzung besteht, wenden Sie sich bitte an admin@php.cn