PHP计算器将持续计算

时间:2015-03-21 18:46:59

标签: php

唯一剩下的问题是,当我尝试使用前一次计算中的值作为起始值完成第二次计算时,答案始终为0.还需要做什么才能连续计算方程?< / p>

<html>
<?php
session_start();
$_SESSION['num1']= 0;
$num1 = $_SESSION['num1'];
if(isset($_POST['num1'])){
    $num1 = $_POST['num1'];
}
if(isset($_POST['num2'])){
    $num2 = $_POST['num2'];
}
if(isset($_POST['calcu'])){
   $calcu = $_POST['calcu'];
}

function calculate($n1,$n2,$calcu){
    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;
    }
    return $compute;
}
// echo "$calcu <br /> <br /> Beginning Number: $num1 <br /> Next Number: $num2 <br /><br />";
 echo "Answer is:" .calculate($num1,$num2, $calcu);
 $_SESSION['num1']=calculate($num1, $num2, $calcu);
?>
<body>
<form action=<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?> method="post">
    Beginning Number:<?php echo $_SESSION['num1'];?><br>
    Next Number: <input type="number"name="num2"><br>
    Calculation: Please type one of the following- Addition, Subtraction, Multiplication, or Division. <input type="text" name="calcu"><br>
    <input type="submit"><br>
</form>
</body>
</html>

1 个答案:

答案 0 :(得分:0)

从你的代码:

$_SESSION['num1']= 0;
$num1 = $_SESSION['num1'];

由于您刚刚将{0}分配给$_SESSION['num1'],因此$num1也将始终为零。

您可能希望将第一个作业包装在条件中:

if (!isset($_SESSION['num1'])) {
    $_SESSION['num1'] = 0;
}