Use PHP to implement simple addition, subtraction, multiplication and division calculator functions

怪我咯
Release: 2023-03-13 14:50:01
Original
9442 people have browsed it

Everyone must have used addition, subtraction, multiplication and division calculators. This article will introduce to you how to use PHP to implement

Calculators based on small programs written in PHP basic language

Requirements: Enter numbers in the input box to perform addition, subtraction, multiplication, and division operations (html+php)

Ideas:

1First create the input numbers and operators In the input box, use the text attribute of input for numbers, and the option attribute of selelct for operators

2. Click the = sign in the input box to perform the corresponding operation,

3 The input box with the = sign can be made using input's submit. Just click the submit form and the content will be passed to php

4 Determine the operator obtained from the html and perform the corresponding operation

5 After the operation is completed, the result must be returned to the form (that is, assigning a value to the form)

The code is as follows:

<?php 
header("content-type:text/html;charset=utf-8"); 
session_start(); 
?> 
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> 
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="zh-CN" dir="ltr"> 
<head> 
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/> 
<title>简单计算机</title> 
</head> 
<body> 
<form action="jisuan.php" method="post"> 
第一个数<input type="text" value="" name="num1"><br /> 
计算符号<select name="oper"> 
<option value="+">+</option> 
<option value="-">-</option> 
<option value="*">*</option> 
<option value="/">/</option> 
</select><br /> 
第二个数<input type="text" value="" name="num2"><br /> 
<input type="submit" value="计算结果"><br /> 
</form> 
</body> 
</html> 
<?php 
$num1=$_POST[&#39;num1&#39;]; 
$num2=$_POST[&#39;num2&#39;]; 
$oper=$_POST[&#39;oper&#39;]; 
$rs=0; 
switch($oper){ 
case "+": 
$rs=$num1+$num2; 
break; 
case "-": 
$rs=$num1-$num2; 
break; 
case "*": 
$rs=$num1*$num2; 
break; 
case "/": 
$rs=$num1/$num2; 
break; 
default: echo "您输入的不正确"; 
} 
$_SESSION[&#39;rs&#39;]=$rs; 
echo &#39;计算结果为:&#39;.$_SESSION[&#39;rs&#39;]; 
?>
Copy after login


The above is the detailed content of Use PHP to implement simple addition, subtraction, multiplication and division calculator functions. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template