0
votes

enter image description hereI need to use the while() loop to print a table of Fahrenheit and Celsius temperature equivalents from –50 degrees F to 50 degrees F in 5-degree increments

To convert from Fahrenheit to Celsius I need subtract 32 from the temperature, multiply by 5, and divide by 9

Looks like conversion works but the Fahrenheit column remains the same

What's the issue here?

<html>
<head>
    <meta charset="UTF-8">
    <title>Unit 3 part 2</title>
</head>
<body>

    <?php
        $min_fahr = -50;
        $max_fahr = 50;
        $celsius = ($max_fahr - 32) * 5 / 9;
    ?>

    <table border="1" cellpadding="3">

        <thead>
            <td>Fahrenheit</td>
            <td>Celsius</td>
        </thead>

        <?php
        while ($min_fahr <= $max_fahr) {

            print "<tr><td>$max_fahr</td><td>$celsius</td></tr>";

            $min_fahr += 5;
            $celsius -= 5;

        } ?>

    </table>

</body>
</html>
3
you need to do the conversion inside the loop - user6763587
but conversion works fine. The original column with Fahrenheit remains on digit 50, why? - Dima Kononenko
What is the expected value of Fahrenheit? - Bluetree
in the range between -50 to 50 with 5 degrees difference - Dima Kononenko

3 Answers

0
votes

You need to put your calculation inside the loop, and print out the value you're actually modifying:

$fahrenheit = -50;

while ($fahrenheit <= 50) {
    $celsius = ($fahrenheit - 32) / 9 * 5;

    print "<tr><td>$fahrenheit</td><td>$celsius</td></tr>";

    $fahrenheit += 5;
} 
0
votes

Your code:

$celsius = ($max_fahr - 32) * 5 / 9;

Does the calculation exactly once. If you want to do the calculation more than once you need to either move that code into the loop:

while( ... ) {
  $celsius = ($some_value - 32) * 5 / 9;
  ...
}

or define a function that you call in the loop:

function F_to_C($deg_f) {
  return ($deg_f - 32) * 5 / 9;
}

while( ... ) {
  $celsius = F_to_C($some_value);
  ...
}

Where the function would be preferable as you probably want to do this calculation elsewhere in your code without having to copy/paste it all over the place.

0
votes

@RobbyCornelissen Thank you, this code works perfectly fine

<html>
<head>
    <meta charset="UTF-8">
    <title></title>
</head>
<body>

    <table border="1" cellpadding="3">

        <thead>
            <td>Fahrenheit</td>
            <td>Celsius</td>
        </thead>

        <?php
        $fahrenheit = 50;

        while ($fahrenheit >= -50) {

            $celsius = ($fahrenheit - 32) * 5 / 9;

            print "<tr><td>$fahrenheit</td><td>$celsius</td></tr>";

            $fahrenheit -= 5;
            $celsius -= 5;

        } ?>

    </table>

</body>
</html>