Quadratic equation solver in php

Kys Plox picture Kys Plox · Apr 16, 2015 · Viewed 9.4k times · Source

I tried to make a quadratic equation solver in php:

index.html:

<html>
    <body>
        <form action="findx.php" method="post">
            Find solution for ax^2 + bx + c<br>
            a: <input type="text" name="a"><br>
            b: <input type="text" name="b"><br>
            c: <input type="text" name="c"><br>
            <input type="submit" value="Find x!">
        </form>   
    </body>
</html>

findx.php:

<?php
    if(isset($_POST['a'])){ $a = $_POST['a']; } 
    if(isset($_POST['b'])){ $b = $_POST['b']; } 
    if(isset($_POST['c'])){ $c = $_POST['c']; }

    $d = $b*$b - 4*$a*$c;
    echo $d;

    if($d < 0) {
        echo "The equation has no real solutions!";
    } elseif($d = 0) {
        echo "x = ";
        echo (-$b / 2*$a);
    } else  {
        echo "x1 = ";
        echo ((-$b + sqrt($d)) / (2*$a));
        echo "<br>";
        echo "x2 = ";
        echo ((-$b - sqrt($d)) / (2*$a));
    }
?>

the problem is that it's returning wrong answers (d is right,x1 and x2 are not) seems like sqrt() is returning zero or maybe something else.

Answer

Chris Brendel picture Chris Brendel · Apr 16, 2015

There's a typo in this line:

elseif($d = 0)

which is assigning the value 0 to $d instead of comparing it. That means you are always evaluating sqrt(0), which is 0, in your else block.

It should be:

elseif($d == 0)