Having written a quadratic equation calculator in PHP, I thought I would have most of my problems with the maths. Not so though, as I am getting very strange output. The program is supposed to $_GET
the values of the x2, x, and other number from a form, calculate the values of x, and then display them. when I first load up the page, the program outputs -10
(even though I have not entered anything into the form) and then does nothing if I enter values. For instance, if I enter 1, 11 and 18
into the text fields, which should output x = -9 and -2
, the program outputs -22
. What am I doing wrong?
Here is my code (the <body>
section of my HTML document):
<body>
<h1>Quadratic equation calculator</h1>
<p>Type the values of your equation into the calculator to get the answer.</p>
<?php
$xsqrd;
$x;
$num;
$ans1 = null;
$ans2 = null;
$errdivzero = "The calculation could not be completed as it attempts to divide by zero.";
$errsqrtmin1 = "The calculation could not be completed as it attempts to find the square root of a negative number.";
$errnoent = "Please enter some values into the form.";
?>
<form name = "values" action = "calc.php" method = "get">
<input type = "text" name = "x2"><p>x<sup>2</sup></p>
<input type = "text" name = "x"><p>x</p>
<input type = "text" name = "num">
<input type = "submit">
</form>
<?php
if ((!empty($_GET['x2'])) && (!empty($_GET['x'])) && (!empty($_GET['num']))) {
$xsqrd = $_GET['x2'];
$x = $_GET['x'];
$num = $_GET['num'];
$ans1 = (-$x) + (sqrt(pow($x, 2) - (4 * $xsqrd * $num))) / (2 * $xsqrd);
$ans2 = (-$x) - (sqrt(pow($x, 2) - (4 * $xsqrd * $num))) / (2 * $xsqrd);
}
?>
<p>
<?php
if(($ans1==null) or ($ans2==null))
{
print $errnoent;
}
else
{
print "x = " + $ans1 + "," + $ans2;
}
?>
</p>
</body>