Hello all!
Got another code that I need a helpful nudge with. I need to create a function to calculate the area of a circle. The function has to take in two arguments (a number and a string). The number is the diameter; the string is the word “diameter.” The function has to return the area of the circle or a -1 for an error. The script has to initialize test variables, call the function and display the results. I’m such a noob so don’t laugh when you see my code thus far. I appreciate any help you can offer.
I’ve quickly thrown together an example of how you might go about this - let me know if you need help understanding/modifying it.
[php]
function circle_area($num,$type=“radius”)
{
if(is_numeric($num) && is_string($type) && !empty($num) && !empty($type))
{
$radius = ($type == “diameter”) ? $num/2 : $num; // Radius is set to half the given number if the type is diameter, or unchanged if radius
$area = pi()*pow($radius,2); // Pi as defined by php multiplied by radius to the power of 2 (squared)
return $area; // Return result
}
else
{
return -1; // Return Pi when invalid/empty values are given
}
}
[/php]
It’s still all just Greek to me. I think I’m sort of getting a grip on it and then I find out I’m not.
I’m going to paste the code again because, apparently, I’ve put something somewhere it doesn’t belong. Still won’t display in the browser.
I checked the syntax in Putty and it had some issues but I couldn’t find them.
Thank you for your help again. I really, really appreciate it so much.
<?php
// variables
$diameter = 6;
$pi = 3.14;
$area = ($diameter * $pi);
$title = "Circle";
function circle_area($num,$type="radius")
{
if(is_numeric($num) && is_string($type) && !empty($num) && !empty($type))
{
$radius = ($type == "diameter") ? $num/2 : $num; // Radius is set to half the given number if the type is diameter, or unchanged if radius
$area = pi()*pow($radius,2); // Pi as defined by php multiplied by radius to the power of 2 (squared)
return $area; // Return result
}
else
{ return -1; // Return Pi when invalid/empty values are given }
}
echo "<html>
<head>
<title>
$title
</title>
</head>
<body>
<h1>Area of a Circle</h1>\n";
echo circle_area(6,"diameter");
echo "</body>
</html>";
?>