我目前正在为练习做一些简单的计算器,但输出或结果未显示在这里是我的代码人们希望你能帮助我:/
<input type="radio" value= "Addition" name="calcu"> Addition .<br />
<input type="radio" value= "Subtraction" name="calcu"> Subtraction .<br />
<input type="radio" value= "Multiplication" name="calcu"> Multiplication .<br />
<input type="radio" value= "Division" name="calcu"> Division .<br />
<?php
$num1 = $_POST['num1'];
$num2 = $_POST['num2'];
$calcu = $_POST['calcu'];
function calculate($n1,$n2)
{
switch('$calcu')
{
case "Addition";
$compute = $n1 + $n2;
break;
case "Subtraction";
$compute = $n1 - $n2;
break;
case "Multiplication";
$compute = $n1 * $n2;
break;
case "Division";
$compute = $n1 / $n2;
break;
}
}
echo "$calcu <br /> <br /> 1st Number: $num1 <br /> 2nd Number: $num2 <br /><br />";
echo "Answer is:" .calculate($num1,$num2);
?>
答案 0 :(得分:2)
这是完整的代码:
<?php
$num1 = $_POST['num1'];
$num2 = $_POST['num2'];
$calcu = $_POST['calcu'];
function calculate($n1,$n2, $calcu) // set $calcu as parameter
{
switch($calcu)
{
case "Addition": // here you have to use colons not semi-colons
$compute = $n1 + $n2;
break;
case "Subtraction":
$compute = $n1 - $n2;
break;
case "Multiplication":
$compute = $n1 * $n2;
break;
case "Division":
$compute = $n1 / $n2;
break;
}
return $compute; // returning variable
}
echo "$calcu <br /> <br /> 1st Number: $num1 <br /> 2nd Number: $num2 <br /><br />";
echo "Answer is:" .calculate($num1,$num2, $calcu); // you need to pass $calcu as argument of that function
?>
答案 1 :(得分:0)
将switch('$calcu')
更改为switch($calcu)
。
正如@PeterM所提到的,您正在访问变量$calcu
超出范围。您可以将$calcu
变量传递给fun calculate
,也可以直接通过$_POST
数组访问。
使用switch($_POST['calcu'])
。
OR
function calculate($n1,$n2, $calcu) {
...
}
通过calculate($n1,$n2, $calcu)
召集乐趣。
答案 2 :(得分:0)
将switch('$calcu')
更改为switch($calcu)
。应该是这样的。
但不仅如此。你的变量是未定义的,因为你试图在表单提交之前解决它们,即它们还不存在。
$num1 = $_POST['num1'];
$num2 = $_POST['num2'];
$calcu = $_POST['calcu'];
你在那里解决它们
echo "$calcu <br /> <br /> 1st Number: $num1 <br /> 2nd Number: $num2 <br /><br />";
echo "Answer is:" .calculate($num1,$num2);
实现此目的的正确方法是检查表单是否已提交:
<input type="radio" value= "Addition" name="calcu"> Addition .<br />
<input type="radio" value= "Subtraction" name="calcu"> Subtraction .<br />
<input type="radio" value= "Multiplication" name="calcu"> Multiplication .<br />
<input type="radio" value= "Division" name="calcu"> Division .<br />
<?php
if (isset($_POST)){
$num1 = $_POST['num1'];
$num2 = $_POST['num2'];
$calcu = $_POST['calcu'];
function calculate($n1,$n2)
{
switch('$calcu')
{
case "Addition";
$compute = $n1 + $n2;
break;
case "Subtraction";
$compute = $n1 - $n2;
break;
case "Multiplication";
$compute = $n1 * $n2;
break;
case "Division";
$compute = $n1 / $n2;
break;
}
}
echo "$calcu <br /> <br /> 1st Number: $num1 <br /> 2nd Number: $num2 <br /><br />";
echo "Answer is:" .calculate($num1,$num2);
unset($_POST);
}
?>