php中的二次方程求解器
我尝试用php制作一个二次方程求解器: index.html:php中的二次方程求解器,php,formula,calculator,equation,quadratic,Php,Formula,Calculator,Equation,Quadratic,我尝试用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: <i
<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>
<?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));
}
?>
找到ax^2+bx+c的解决方案
答:
b:
c:
findx.php:
<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>
<?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));
}
?>
问题是它返回了错误的答案(d是对的,x1和x2不是),似乎sqrt()返回了零或者其他东西。这一行有一个输入错误:
elseif($d=0)
它将值0
分配给$d
,而不是对其进行比较。这意味着您总是在else
块中计算sqrt(0)
,即0
应该是:
elseif($d==0)
对于哪些输入参数,您得到了什么结果?您期望得到什么呢?在这样的赋值至少不会给出警告的语言中,一个有用的习惯是将常量放在左边:if(0=$d)
将失败。