php面向对象编程练习:计算矩形、三角形、圆形的周长和面积

刚刚学完php面向对象的编程,参考着高洛峰老师的php教程学习了这个实例。

效果图片:

三角形
矩形
圆形

以下是实现代码:

index.php

<html>
<head>
    <title>图形计算(使用面向对象开发技术)</title>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
</head>
<body>
    <center>
        <h1>图形(周长&面积) 计算器</h1>
        <a href="index.php?action=rect">矩形</a>
        <a href="index.php?action=triangle">三角形</a>
        <a href="index.php?action=circle">圆形</a>
        <hr>
    </center>


    <?php  //php代码部分
        error_reporting(E_ALL & ~E_NOTICE);//提示错误的等级
    // __autoload是php中的魔术方法,在用到类的时候自动调用
        function __autoload($className){
            //自动导入这个类
            include strtolower($className).".class.php";
        }
        //输出表单,form类中有魔术方法__toString,因此可以直接输出类的对象引用,就是输出对象返回的字符串
        echo new Form();

        if(isset($_POST["sub"])){
            //输出结果
            echo new Result();//直接输出对象的引用表示
        }

    ?>

</body>
</html>
form.class.php_这是表单类_
<?php
    //根据index中提交的不同action的值返回不同的表单
    class Form{
   
        private $action;
        private $shape;
        //构造方法
        function __construct($action=""){
   
            $this->action = $action;
            $this->shape=isset($_REQUEST["action"])?$_REQUEST["action"]:"rect";
        }

        
  • 16
    点赞
  • 65
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
好的,这是一个技术问题,我很乐意为您解答。对于计算圆形矩形面积周长,您需要先定义一个圆形类和一个矩形类,并在其中分别定义计算面积周长的方法。以下是可能的实现: ```java // 圆形类 public class Circle { private double radius; public Circle(double radius) { this.radius = radius; } public double getRadius() { return radius; } public void setRadius(double radius) { this.radius = radius; } public double getArea() { return Math.PI * radius * radius; } public double getPerimeter() { return 2 * Math.PI * radius; } } // 矩形类 public class Rectangle { private double width; private double height; public Rectangle(double width, double height) { this.width = width; this.height = height; } public double getWidth() { return width; } public void setWidth(double width) { this.width = width; } public double getHeight() { return height; } public void setHeight(double height) { this.height = height; } public double getArea() { return width * height; } public double getPerimeter() { return 2 * (width + height); } } ``` 使用以上代码,您可以创建圆形矩形的对象,并调用各自的方法来计算面积周长。例如: ```java Circle circle = new Circle(5); System.out.println("圆形面积为:" + circle.getArea()); System.out.println("圆形周长为:" + circle.getPerimeter()); Rectangle rectangle = new Rectangle(3, 4); System.out.println("矩形面积为:" + rectangle.getArea()); System.out.println("矩形周长为:" + rectangle.getPerimeter()); ``` 以上代码输出的结果应该为: ``` 圆形面积为:78.53981633974483 圆形周长为:31.41592653589793 矩形面积为:12.0 矩形周长为:14.0 ```

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值