Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Quadratic equation solver in php

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.

like image 333
Kys Plox Avatar asked Jul 25 '26 21:07

Kys Plox


1 Answers

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)

like image 53
Chris Brendel Avatar answered Jul 28 '26 12:07

Chris Brendel



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!