php 中的二次方程求解器
Quadratic equation solver in php
我试图在 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));
}
?>
问题是它返回了错误的答案(d 是正确的,x1 和 x2 不是)似乎 sqrt() 正在返回零或其他东西。
这一行有错别字:
elseif($d = 0)
这是分配值0
到$d
而不是比较它。这意味着您总是在 else
块中评估 sqrt(0)
,即 0。
应该是:
elseif($d == 0)
我试图在 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));
}
?>
问题是它返回了错误的答案(d 是正确的,x1 和 x2 不是)似乎 sqrt() 正在返回零或其他东西。
这一行有错别字:
elseif($d = 0)
这是分配值0
到$d
而不是比较它。这意味着您总是在 else
块中评估 sqrt(0)
,即 0。
应该是:
elseif($d == 0)