PHP二次方程计算器奇怪的输出

时间:2013-03-09 10:49:47

标签: php calculator quadratic

用PHP编写了二次方程式计算器,我以为我的数学问题大部分都存在。不是这样,因为我的输出非常奇怪。该程序应该$_GET x 2 ,x的值和表格中的其他数字,计算x的值,然后显示它们。当我第一次加载页面时,程序输出-10(即使我没有在表单中输入任何内容),如果输入值,则不执行任何操作。例如,如果我在输出1, 11 and 18的文本字段中输入x = -9 and -2,则程序会输出-22。我做错了什么?

以下是我的代码(我的HTML文档的<body>部分):

<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>
&nbsp;
<input type = "text" name = "x"><p>x</p>
&nbsp;
<input type = "text" name = "num">
&nbsp;
<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>

1 个答案:

答案 0 :(得分:1)

你有两个错误。

第一个是数学,应该是

$ans1 = ((-$x) + (sqrt(pow($x, 2) - (4 * $xsqrd * $num)))) / (2 * $xsqrd);
$ans2 = ((-$x) - (sqrt(pow($x, 2) - (4 * $xsqrd * $num)))) / (2 * $xsqrd);

正确的公式是(-b+-sqrt(b^2-4ac))/(2a)而不是-b+sqrt(b^2-4ac)/(2a) - 在后一种情况下,除了括号之外,除法优先于加法。

第二个是输出结果的方式,你应该使用连接运算符.

print "x = " . $ans1 . "," . $ans2;

(虽然我会使用echo代替print