【问题标题】:My comparison operator is not working for PHP in atom [closed]我的比较运算符不适用于原子中的 PHP [关闭]
【发布时间】:2021-03-21 00:17:53
【问题描述】:

我试图在 $BMI 和数字之间进行比较,但是它显示“解析错误:语法错误,意外标记“

对于 HTML

 <!DOCTYPE html>
<html lang="en" dir="ltr">
  <head>
    <meta charset="utf-8">
    <title>BMI Calculator</title>
    <link rel="stylesheet" href="style1.css">
  </head>

  <body>
    <form action="BMI.php" method="post">
      <table>
        <tr>
          <td><label for="">Weight (kg):</label></td>
          <td><input type="text" name="weight" value=""></td>
        </tr>
        <tr>
          <td><label for="">Height (m):</label></td>
          <td><input type="text" name="height" value=""></td>
        </tr>
      </table>
      <input type="submit" name="calt" value="Calculate">
      <input type="reset" name="reset" value="Clear">
    </form>
  </body>
  
</html>

对于 PHP

<?php

$weight = $_POST['weight'];
$height = $_POST['height'];

function calculateBMI(){
  global $weight, $height;
  $total = ($weight/($height*$height))*10000;
  return $total;
}

$BMI = calculateBMI();
echo "Your BMI is ". number_format((float)$BMI,2,'.','');

if ($BMI < 18.5){
  echo "You are underweight";}
elseif (18.5 <= $BMI <= 25 ){
  echo "You are normal weight";}
elseif (26 <= $BMI <= 30){
  echo "You are overweight"}
elseif (31 <= $BMI <= 40){
  echo "You are obese";}
elseif ($BMI > 40){
  echo "Out of bound";}

?>

谢谢你帮助我>

【问题讨论】:

  • 尝试拆分双重比较。所以把18.5 &lt;= $BMI &lt;= 25改成18.5 &lt;= $BMI &amp;&amp; $BMI &lt;= 25
  • 如果 BMI 为 25.5 会怎样?
  • @Tintenfisch,检查下一个,但 25.5 小于 26,因此被跳过...
  • @NigelRen 哦,等等,我把 $BMI 和实际值混淆了(因为我习惯将变量放在左边)facepalm

标签: php html forms


【解决方案1】:

如果您想检查 BMI 是否低于或等于 18.5 但低于 25,您可以使用:

($BMI <= 18.5 && $BMI < 25)

但您不需要这些双重检查。这可能就是你想要的:

if ($BMI <= 0) {
    echo "BMI must be greater than 0.";
} elseif ($BMI < 18.5) {
    echo "You are underweight";
} elseif ($BMI <= 25) {
    echo "You are normal weight";
} elseif ($BMI <= 30) {
    echo "You are overweight";
} elseif ($BMI <= 40) {
    echo "You are obese";
// $BMI is > 40
} else {
    echo "Out of bound";
}

【讨论】:

    【解决方案2】:

    您可以尝试使用(18.5 &lt;= $BMI &amp;&amp; $BMI &lt;= 25 ),而不是使用(18.5 &lt;= $BMI &lt;= 25 ) 这种语法。

    所以你最后的 if-else 块将是这样的:

    if ($BMI < 18.5){
      echo "You are underweight";}
    elseif (18.5 <= $BMI && $BMI <= 25 ){
      echo "You are normal weight";}
    elseif (26 <= $BMI && $BMI <= 30){
      echo "You are overweight"}
    elseif (31 <= $BMI && $BMI <= 40){
      echo "You are obese";}
    elseif ($BMI > 40){
      echo "Out of bound";}
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-08-21
      • 1970-01-01
      • 1970-01-01
      • 2016-12-31
      • 2013-09-16
      • 1970-01-01
      相关资源
      最近更新 更多