form表單實現簡易計算:
<!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"> <head> <title> 計算器 </title> <meta name="generator" content="editplus" /> <meta name="author" content="" /> <meta name="keywords" content="" /> <meta name="description" content="" /> </head> <body> <form action="calculator.php" method="post"> <input type="text" name="num1"/> <select name="jisuan"> <option>+</option> <option>-</option> <option>*</option> <option>/</option> </select> <input type="text" name="num2"/> <input type="submit" name="num3" value="計算"/> </form>
<?php if(isset($_POST['num3'])){//首先在開始以前要先判斷是否已經傳值 $num1=$_POST['num1']; $num2=$_POST["num2"]; $num3=$_POST["num3"]; $jisuan=$_POST["jisuan"]; switch($jisuan){ //switch語句實現 case '+': $num3=$num1+$num2; break; case '-': $num3=$num1-$num2; break; case '*': $num3=$num1*$num2; break; case '/': if($num2==0){//進行除法運算時 首先要先判斷除數,除數爲0時直接echo echo "被除數不能爲0"; echo $num3=''; }else{ $num3=$num1/$num2; } break; } echo $num3; } ?>
<?php if(isset($_POST['num3'])){ $num1=$_POST['num1']; $num2=$_POST['num2']; $num3=$_POST['num3']; $jisuan=$_POST['jisuan']; if($jisuan=='+'){ $num3=$num1+$num2; }elseif($jisuan=='-'){ $num3=$num1-$num2; }elseif($jisuan=='*'){ $num3=$num1*$num2; }elseif($jisuan='/'){ $num3=$num1/$num2; if($num2==0){ echo "被除數不能爲0"; echo $num3=''; }else{ $num3=$num1/$num2; } } echo $num3; } ?>
</body> </html>