使用php函数计算圆的面积

时间:2011-01-26 22:22:51

标签: php

我需要创建一个计算圆形区域的函数。该函数应该包含两个参数(数字和字符串)。数字应该是圆的半径或直径。该字符串应为“直径”一词。该函数应返回圆的区域,或返回-1表示错误。最后,脚本应初始化测试变量,调用函数并将结果显示为网页。

这是PHP的开始,但我只是遇到了问题。谢谢!

这是我到目前为止所得到的,但它没有返回-1,我无法弄清楚如何做到这一点。

$diameter = 4.0;
$pi = 3.14;
$title="Circle";

echo "<html> <head> <title> $title </title> </head> <body>";

function circleArea($diameter, $pi) 
{
    $area = $diameter * $pi; 
    return $area; 
} 

echo circleArea ($diameter,$pi); 
echo "</body> </html>";

3 个答案:

答案 0 :(得分:3)

<?php
function calculateAreaOfCircle($number = 1, $type = 'radius') {
  if(!is_numeric($number) || $number <= 0)
    return -1;

  // what type of number is it?
  switch($type) {
    case 'radius':
    default:
      $radius = $number;

      break;

    case 'diameter':
      $radius = $number / 2;

      break;
  }

  return pow($radius, 2) * M_PI;
}

// what is the area for the radius of 25?
echo(calculateAreaOfCircle(25));

// what is the area for the diameter of 30?
echo(calculateAreaOfCircle(30, 'diameter'));
?>

当你告诉我字符串是什么时候...... ;-)(我想我已经猜到了)

答案 1 :(得分:0)

<?php  
/**
* 
*/
class mathAlgorithm
{
    public $pie;
    public function __construct($pie)
    {
        $this->pie = $pie;
    }
    public function AreaOfCircle($radius)
    {
        $pie = $this->pie;
        /**
        * Where Area of a Circle
        * A = πr2
        * Let   A = $area
        *       π = $pie
        *       r = $radius
        *   Where π = 22/7 or 3.142
        */
        $area = $pie * pow($radius, 2);
        $area = round($area, 2);
        return $area;
    }
}
$math = new mathAlgorithm(3.142);
echo $math->AreaOfCircle(2);
?>

答案 2 :(得分:-3)

<?php
    $radius=2;
    $length=2;
    $breadth=2;
    $pi = 3.14;
    $area1= $pi * $radius * $radius;
    $area2=2*$pi*$radius;
    $rectangle1=$length*$breadth;
    $rectangle2=2*($length+$breadth);
    echo "AREA OF CIRCLE = $area1";
    echo "<br><br>";
    echo "PERIMETER OF RECTANGLE = $area2";
    echo "<br><br>";
    echo "AREA OF RECTANGLE = $rectangle1";
    echo "<br><br>";
    echo "PERIMETER OF RECTANGLE = $rectangle2";
?>