3

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.

1
  • What results did you get for what input parameters? And what did you expect? Commented Apr 16, 2015 at 12:44

1 Answer 1

4

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)

Sign up to request clarification or add additional context in comments.

1 Comment

In languages where such assignments doesn't give at least a warning, a useful habit is to put the constant on the left: if (0 = $d) will fail.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.