用php求矩形周长,PHP实现的简单三角形、矩形周长面积计算器分享
運用php面向對象的知識設計一個圖形計算器,同時也運用到了抽象類知識,這個計算器可以計算三角形的周長和面積以及矩形的周長和面積。本圖形計算器有4個頁面:1.php圖形計算器主頁index.php;??? 2.形狀的抽象類shape.class.php;??? 3三角形計算類triangle.class.php;??? 4.矩形計算類rect.class.php。
php圖形計算器代碼點擊下載:
代碼分別如下:
php圖形計算器主頁:
簡單的圖形計算器簡單的圖形計算器
矩形 ||
三角形
error_reporting(e_all & ~e_notice);
//設置自動加載這個程序需要的類文件
function __autoload($classname){
include strtolower($classname).".class.php";
}
//判斷用戶是否有選擇單擊一個形狀鏈接
if(!empty($_get['action'])) {
//第一步:創建形狀的對象
$classname = ucfirst($_get['action']);
$shape=new $classname($_post);
//第二步:調用形狀的對象中的界面view()
$shape -> view();
//第三步:用戶是否提交了對應圖形界面的表單
if(isset($_post['dosubmit'])) {
//第四步:查看用戶輸出的數據是否正確, 失敗則提示
if($shape->yan($_post)) {
//計算圖形的周長和面積
echo $shape->name."的周長為:".$shape->zhou()."
";
echo $shape->name."的面積為:".$shape->area()."
";
}
}
//如果用戶沒有單擊鏈接, 則是默認訪問這個主程序
}else {
echo "請選擇一個要計算的圖形!
";
}
?>
形狀的抽象類:
abstract class? shape{
//形狀的名稱
public $name;
//形狀的計算面積方法
abstract function area();
//形狀的計算周長的方法
abstract function zhou();
//形狀的圖形表單界面
abstract function view();
//形狀的驗證方法
abstract function yan($arr);
}
三角形計算類文件:
class triangle extends shape {
private $bian1;
private $bian2;
private $bian3;
function __construct($arr = array()) {
if(!empty($arr)) {
$this->bian1 = $arr['bian1'];
$this->bian2 = $arr['bian2'];
$this->bian3 = $arr['bian3'];
}
$this->name = "三角形";
}
function area() {
$p =??? ($this->bian1 + $this->bian2 + $this->bian3)/2;
return sqrt($p*($p-$this->bian1)*($p-$this->bian2)*($p-$this->bian3));
}
function zhou() {
return $this->bian1 + $this->bian2 + $this->bian3;
}
function view() {
$form = '
';$form .= $this->name.'第一個邊:
';
$form .= $this->name.'第二個邊:
';
$form .= $this->name.'第三個邊:
';
$form .= '
';
$form .='
';echo $form;
}
function yan($arr) {
$bj = true;
if($arr['bian1'] < 0) {
echo "第一個邊不能小于0!
";
$bj = false;
}
if($arr['bian2'] < 0) {
echo "第二個邊不能小于0!
";
$bj = false;
}
if($arr['bian3'] < 0) {
echo "第三個邊不能小于0!
";
$bj = false;
}
if(($arr['bian1']+$arr['bian2'] < $arr['bian3']) || ($arr['bian1'] + $arr['bian3'] < $arr['bian2']) || ($arr['bian2']+$arr['bian3'] < $arr['bian1'])) {
echo "兩邊之和必須大于第三個邊";
$bj = false;
}
return $bj;
}
}
矩形計算類文件:
class rect extends shape {
private $width;
private $height;
function __construct($arr=array()) {
if(!empty($arr)) {
$this->width = $arr['width'];
$this->height = $arr['height'];
}
$this->name = "矩形";
}
function area() {
return $this->width * $this->height;
}
function zhou() {
return 2*($this->width + $this->height);
}
function view() {
$form = '
';$form .= $this->name.'的寬:
';
$form .= $this->name.'的高:
';
$form .= '
';
$form .='
';echo $form;
}
function yan($arr) {
$bg = true;
if($arr['width'] < 0) {
echo $this->name."的寬不能小于0!
";
$bg = false;
}
if($arr['height'] < 0) {
echo $this->name."的高度不能小于0!
";
$bg = false;
}
return $bg;
}
}
希望與廣大網友互動??
點此進行留言吧!
總結
以上是生活随笔為你收集整理的用php求矩形周长,PHP实现的简单三角形、矩形周长面积计算器分享的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: DNF黑暗武士带什么武器
- 下一篇: php试卷A高质量含答案,php试卷A高