1. 程式人生 > 程式設計 >PHP實現計算器小功能

PHP實現計算器小功能

本文例項為大家分享了PHP實現計算器小功能的具體程式碼,供大家參考,具體內容如下

<?php
 if (isset($_POST['sub'])) {
 $f = true;
 $error = "有以上問題: <br>";
 if ($_POST["num1"] == "") {
  $f = false;
  $error .= "第一個數不能為空.<br>";
 } else {
   if(!is_numeric($_POST[num1])) {
    $f = false;
    $error .= "第一個數字不是數字.<br>";
   }
 }
 if ($_POST['num2'] == "") {
  $f = false;
  $error .= "第二個數字不能為空.<br>";
 } else {
   if (!is_numeric($_POST['num2'])) {
   $f = false;
   $error .= "第二個數字不是數字<br>";
  }
 }
 if ($f) {
  switch ($_POST['ysf']) {
  case '+': $sum = $_POST['num1']+$_POST['num2'];
   break;
  case '-': $sum = $_POST['num1']-$_POST['num2'];
   break;
  case '*': $sum = $_POST['num1']*$_POST['num2'];
   break;
  case '/': $sum = $_POST['num1']/$_POST['num2'];
   break;
  case '%': $sum = $_POST['num1']%$_POST['num2'];
   break;
  }
 }
 }
?>
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>簡易計算器</title>
<style>
 * {
  margin: 0px;
 padding: 0px;
 }
 #contains {
  width: 400px;
 margin: 50px auto;
 }
 h1 {
  width: 400px;
 text-align: center;
 color: #0F0;
 }
 table {
  margin-top: 20px;
 width: 400px;
 }
 input {
  background: yellow;
 border-radius: 20px;
 }
 input:hover {
  background: green;
 }
 select {
  background: yellow;
 border-radius: 20px;
 }
 td {
  background: #3F0;
 text-align: center;
 height: 30px;
 }
 #sub {
  border-radius: 25px;
 width: 50px;
 }
</style>
</head>
 
<body>
 <div id="contains">
  <h1>簡易計算器</h1>
 <form action="Calculator.php" method="post">
 <table border="0">
  <tr>
  <td><input type="text" name="num1" value="<?php echo $_POST['num1'];?>" size="3"/></td>
  <td>
   <select name="ysf">
   <option <?php if($_POST['ysf'] == "+") echo "selected";?> value="+">+</option>
   <option <?php if($_POST['ysf'] == "-") echo "selected";?> value="-">-</option>
   <option <?php if($_POST['ysf'] == "*") echo "selected";?> value="*">*</option>
   <option <?php if($_POST['ysf'] == "/") echo "selected";?> value="/">/</option>
   <option <?php if($_POST['ysf'] == "%") echo "selected";?> value="%">%</option>
   </select>
  </td>
  <td><input type="text" name="num2" value="<?php echo $_POST['num2'];?>" size="3"/></td>
  <td><input type="submit" id = 'sub' name="sub" value="計算"/></td>
  </tr>
  <tr>
   <td colspan="4">
   <?php
    if ($f) {
    echo "計算結果: {$_POST['num1']}{$_POST['ysf']}{$_POST['num2']} = {$sum}";
   } else {
    echo "$error";
   }
   ?>
  </td>
  </tr>
 </table>
 </form>
 </div>
</body>
</html>

PHP實現計算器小功能

以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支援我們。