settingsAccountsettings
By using our mini forum, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy
Menusettings

Q: Script to convert Celsius to Fahrenheit and Fahrenheit to Celsius (Code)

+2 votes
  • Write a PHP script to convert from Celsius to Fahrenheit
  • Print the result in format "132.8 °F = 56 °C" (use ° for °)
  • Define the degree conversion functions:
function celsiusToFahrenheit(float $celsius) : float
{
    return $celsius * 1.8 + 32;
}

function fahrenheitToCelsius(float $fahrenheit) : float
{
    return ($fahrenheit - 32) / 1.8;
}

 

asked in PHP category by user ak47seo
edited by user golearnweb

1 Answer

+1 vote
 
Best answer

Here is the solution:

<!DOCTYPE html>
<html>
<head>
    <title>Convert</title>
</head>

<body>

<?php

function celToFah(float $degrees)
{
    return $degrees * 1.8 + 32;
}

function fahToCel(float $degrees)
{
    return ($degrees - 32) / 1.8;
}

if (isset($_GET['cel'])) {
    $cel = floatval($_GET['cel']);
    $fah = celToFah($cel);
    $fahMsg = "$cel &deg;C = $fah &deg;F";
}

if (isset($_GET['fah'])) {
    $fah = floatval($_GET['fah']);
    $cel = fahToCel($fah);
    $celMsg = "$fah &deg;F = $cel &deg;C";
}

?>


<form>
    Celsius: <input type="number" name="cel">
    <input type="submit" value="Convert Celsius to Fahrenheit">
    <?php
    if (isset($fahMsg)) {
        echo $fahMsg;
    }
    ?>
</form>
<br>
<form>
    Fahrenheit: <input type="number" name="fah">
    <input type="submit" value="Convert Fahrenheit to Celsius">
    <?php
    if (isset($celMsg)) {
        echo $celMsg;
    }
    ?>
</form>

</body>
</html>

 

answered by user andrew
selected by user golearnweb
...