非常基本的 PHP 计算器:无法计算出我做错了什么

Very basic PHP calculator: can't work out what I'm doing incorrectly

我只是在做一个相当蹩脚的计算器,因为我正在开始学习 PHP。我不明白为什么一切似乎都很好,只是答案不会显示。

这是HTML:

<head>
<meta charset="utf-8">
<title>A (Seriously) Simple Calculator</title>
<link rel="stylesheet" type="text/css" href="./calc_css.css">
</head>
<body>
<form method="post" attribute="post" action="calc1.php">

<p>First Value:<br/>
<input type="number" id="first" name="first" step="0.0000000001"></p>
<p>Second Value:<br/>
<input type="number" id="second" name="second" step="0.0000000001"></p>

<p>+<input type="radio" name="operation" id="add" value="add" checked="true"></p><br/>
<p>-<input type="radio" name="operation" id="subtract" value="subtract"></p><br/>
<p>X<input type="radio" name="operation" id="multiply" value="multiply"></p><br/>
<p>/<input type="radio" name="operation" id="divide" value="divide"></p><br/>

<p></p>
<button type="submit" name="answer" id="answer" value="answer">Calculate</button>
</form>
</body>
</html>

这是我的 PHP:

<html>

<head>
<meta charset="utf-8">
<title>Answer</title>
</head>

<body>
<p>The answer is: 

<?php
$first = floatval($_POST['first']);
$second = floatval($_POST['second']);

if($_POST['operation'] == 'add') {
echo $first + $second;
}
else if($_POST['operation'] == 'subtract') {
echo $first - $second;
}
else if($_POST['operation'] == 'multiply') {
echo $first * $second;
}
else($_POST['operation'] == 'divide') {
echo $first / $second;
}

?>

</p> 
</body>
</html>

我认为这与我的输入步骤或类型无关,我已经在我的 PHP 文件中尝试了所有方式(我能想到的)。也就是说,我是一个非常绿色的初学者。任何帮助将不胜感激。

问题是你的最后一个条件语句是 else 而不是另一个 else if

else($_POST['operation'] == 'divide') {
echo $first / $second;
}

将错误报告设置为捕获和显示,会抛出如下内容:

Parse error: syntax error, unexpected '{' in /var/usr/you/folder/file.php on line 24

改为:

else if($_POST['operation'] == 'divide') {
echo $first / $second;
}

error reporting 添加到您的文件的顶部,这将有助于查找错误。

<?php 
error_reporting(E_ALL);
ini_set('display_errors', 1);

// rest of your code

旁注:显示错误只应在试运行中进行,绝不能在生产中进行。

它假设 else($_POST['operation'] == 'divide') 将始终与 "divide" 进行比较,而不是 else { $var=x; } 作为 "assign this variable to "x",从而抛出一个错误。

来自手册:http://php.net/manual/en/control-structures.elseif.php

<?php
if ($a > $b) {
    echo "a is bigger than b";
} elseif ($a == $b) {
    echo "a is equal to b";
} else {
    echo "a is smaller than b";
}
?>

其他参考资料:

您的代码中存在错误,请查看您 PHP 代码中的最后一个 "else" 语句。

<?php
    if($_POST['operation'] == 'add') {
        echo $first + $second;
    }
    else if($_POST['operation'] == 'subtract') {
        echo $first - $second;
    }
    else if($_POST['operation'] == 'multiply') {
        echo $first * $second;
    }
    else if($_POST['operation'] == 'divide') {
        if($second == 0){
            echo 'Cannot divide by 0';
        } else {
            echo $first / $second;
        }
    } else {
        echo 'unknown operator';
    }
?>

另请记住,您不能除以 0,因为它会在 PHP 中创建一条警告消息。

因此,在编写和测试 "Fred -ii-" 答案中显示的代码时,最好启用 error_reporting。