博客列表 >实现一个简单的计算器功能

实现一个简单的计算器功能

手机用户1617360551
手机用户1617360551原创
2021年10月14日 16:27:51721浏览

实现一个简单的计算器功能

  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <meta charset="UTF-8">
  5. <meta http-equiv="X-UA-Compatible" content="IE=edge">
  6. <meta name="viewport" content="width=device-width, initial-scale=1.0">
  7. <title>计算器</title>
  8. <style>
  9. body{
  10. background-color: #ccc;
  11. }
  12. h3{
  13. color: lightseagreen;
  14. }
  15. </style>
  16. </head>
  17. <body>
  18. <h3>计算器</h3>
  19. <form action="" method="post">
  20. <!-- !第一个数字 -->
  21. <input type="number" name="number1" value="<?= isset($_POST['number1']) ? $_POST['number1'] : '' ?>">
  22. <select name="opt" id="">
  23. <option value="1" <?php echo isset($_POST['opt']) && $_POST['opt'] == '1' ? 'selected' : '' ?>>+</option>
  24. <option value="2" <?php echo isset($_POST['opt']) && $_POST['opt'] == '2' ? 'selected' : '' ?>>-</option>
  25. <option value="3" <?php echo isset($_POST['opt']) && $_POST['opt'] == '3' ? 'selected' : '' ?>>*</option>
  26. <option value="4" <?php echo isset($_POST['opt']) && $_POST['opt'] == '4' ? 'selected' : '' ?>>/</option>
  27. <option value="5" <?php echo isset($_POST['opt']) && $_POST['opt'] == '5' ? 'selected' : '' ?>>%</option>
  28. </select>
  29. <input type="number" name="number2" value="<?php echo isset($_POST['number2']) ?>">
  30. <input type="submit" name="sub" value="计算">
  31. </form>
  32. </body>
  33. </html>
  34. <?php
  35. // echo $_POST['number1'];
  36. $error = '';
  37. if(($_POST['opt'] == 4 || $_POST['opt'] == 5) && $_POST['num2'] === 0)
  38. {
  39. $error .= '除法运算的时候,第二个值不能为0';
  40. }elseif(empty($_POST['number1']))
  41. {
  42. $error .= '请输入第一个数!!!';
  43. }elseif(empty($_POST['number2'])){
  44. $error .= '请输入第二个数!!!!';
  45. }
  46. if(isset($_POST['sub'])){
  47. if(empty($error)){
  48. switch($_POST['opt'])
  49. {
  50. case $_POST['opt'] == 1:
  51. $answer = $_POST['number1'] + $_POST['number2'];
  52. break;
  53. case $_POST['opt'] == 2:
  54. $answer = $_POST['number1'] - $_POST['number2'];
  55. break;
  56. case $_POST['opt'] == 3:
  57. $answer = $_POST['number1'] * $_POST['number2'];
  58. break;
  59. case $_POST['opt'] == 4:
  60. $answer = $_POST['number1'] / $_POST['number2'];
  61. break;
  62. case $_POST['opt'] == 5:
  63. $answer = $_POST['number1'] % $_POST['number2'];
  64. break;
  65. }
  66. echo '您的答案:'.$answer;
  67. }else{
  68. echo $error;
  69. }
  70. }

声明:本文内容转载自脚本之家,由网友自发贡献,版权归原作者所有,如您发现涉嫌抄袭侵权,请联系admin@php.cn 核实处理。
全部评论
文明上网理性发言,请遵守新闻评论服务协议