• 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>
    12                 alert('第一个数不合法');
    13             </script>
    14 ERROR;
    15         return $error;
    16     }
    17     if(!isset($num2) || !is_numeric($num2)){
    18         $error = <<<ERROR
    19             <script>
    20                 alert('第二个数不合法');
    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>
    36                     alert('第二个数不能为0');
    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 <h2>用php写的基础计算器</h2>
    52 <form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
    53     第一个数:<input type="text" name="num1" /><p>
    54     操作符:<select name="oper">
    55                 <option value="+"> + </option>
    56                 <option value="-"> - </option>
    57                 <option value="*"> * </option>
    58                 <option value="/"> / </option>
    59            </select><p>
    60     第二个数:<input type="text" name="num2" /><p>
    61     <input type="submit" value="计算" />
    62 
    63 </form>
    64 计算结果为:<?php echo isset($res)?$res:""; ?>
    View Code
  • 相关阅读:
    【代码笔记】iOS-GCD用法
    【代码笔记】iOS-DropDownDemo-下拉按钮效果
    【代码笔记】iOS-cell自动变化大小
    【代码笔记】iOS-cell折叠
    【代码笔记】iOS-archive保存图片到本地
    【代码笔记】iOS-左右可滑动的选择条
    【代码笔记】iOS-自动成表格的效果
    【代码笔记】iOS-自定义选择框
    【代码笔记】iOS-实现网络图片的异步加载和缓存
    【代码笔记】iOS-自定义开关
  • 原文地址:https://www.cnblogs.com/qzjpkfj/p/4049423.html
Copyright © 2020-2023  润新知