Applied Programming/Conditions/PHP
conditions.php
edit<?php
// This program converts a Fahrenheit temperature to Celsius.
//
// Input:
// Fahrenheit temperature
//
// Output:
// Fahrenheit temperature
// Celsius temperature
//
// Example:
// Enter Fahrenheit temperature:
// 100
// 100.0° Fahrenheit is 37.8° Celsius
//
// References:
// * http://www.mathsisfun.com/temperature-conversion.html
// * http://php.net/manual/en/features.commandline.io-streams.php
// * https://stackoverflow.com/questions/481466/php-string-to-float
define('ABSOLUTE_ZERO', -459.67);
function get_fahrenheit() {
/* Gets Fahrenheit temperature.
Args:
None
Returns:
float: Fahrenheit temperature
Exits:
ValueError: If Fahrenheit temperature is not a valid float.
ValueError: If Fahrenheit temperature is below absolute zero.
*/
try {
echo "Enter Fahrenheit temperature:";
$fahrenheit = rtrim(fgets(STDIN));
if ($fahrenheit < ABSOLUTE_ZERO) {
throw new Exception("Fahrenheit temperature cannot be below
absolute zero.");
} elseif (!(is_numeric($fahrenheit))) {
throw new Exception("Fahrenheit temperature must be a floating
point value.");
}
return $fahrenheit;
} catch (Exception $e) {
echo $e->getMessage() . "\n";
echo "Value error: '" . $fahrenheit . "' is invalid.";
exit();
}
}
function fahrenheit_to_celsius($fahrenheit) {
/* Converts Fahrenheit temperature to Celsius.
Args:
fahrenheit (float): Fahrenheit temperature to be converted
Returns:
float: Celsius temperature
Exits:
ValueError: If Fahrenheit temperature is not a valid float.
ValueError: If Fahrenheit temperature is below absolute zero.
*/
try {
if (!(is_numeric($fahrenheit))) {
throw new Exception ("Fahrenheit temperature must be a
floating point value.");
}
elseif ($fahrenheit < ABSOLUTE_ZERO) {
throw new Exception("Fahrenheit temperature cannot be below
absolute zero.");
}
} catch (Exception $e) {
echo $e->getMessage() . "\n";
echo "Received '" . $fahrenheit . "'";
exit();
}
define ('TEMPERATURE_DIFFERENCE', 32);
define ('TEMPERATURE_RATIO', 5 / 9);
$celsius = round(($fahrenheit - TEMPERATURE_DIFFERENCE) *
TEMPERATURE_RATIO, 1);
return $celsius;
}
function display_results($fahrenheit, $celsius) {
/* Displays Fahrenheit and Celsius temperatures.
Args:
fahrenheit (float): Fahrenheit temperature
celsuis (float): Celsius temperature
Returns:
None
Raises:
AssertionError: If Fahrenheit temperature is not a valid float.
AssertionError: If Celsius temperature is not a valid float.
*/
assert (is_numeric($fahrenheit), "Fahrenheit must be a float.
Received " . gettype($fahrenheit));
assert (is_numeric($celsius), "Celsius must be a float.
Received " . gettype($celsius));
echo $fahrenheit . "° Fahrenheit is " . $celsius . "° Celsius";
}
function main() {
$fahrenheit = get_fahrenheit();
$celsius = fahrenheit_to_celsius($fahrenheit);
display_results($fahrenheit, $celsius);
}
main();
?>
Try It
editCopy and paste the code above into one of the following free online development environments or use your own PHP compiler / interpreter / IDE.