表单使用函数计算BMI并显示不同的注释.致命错误,显示不正确


Form using function calculate BMI and display different comment. Fatal error and not displaying correctly

我正在创建一个使用函数计算BMI的表单。两个问题。

  1. 注释(体重不足/正常体重/…)的输出应根据计算出的BMI而有所不同,但无论BMI值是多少,它总是输出underweight。我需要做什么才能让它工作?

  2. "致命错误:调用…中未定义的函数bmi()"尽管该函数有效,但仍显示致命错误。有人能教我如何摆脱这个错误吗?非常感谢。

    <form name="bmi" method="GET" action="test.php">
      Mass in kilogram (kg):
      <input type="text" name="mass" id="mass" size="15">
      <br> 
      Height in meter (m):
      <input type="text" name="height" id="height" size="15">
      <br>
      <input type="submit" name="submit" id="submit" value="submit">
    </form>
    <?php
    if ($_GET['submit']) { 
      $mass = $_GET['mass'];
      $height = $_GET['height'];
      function bmi($mass,$height) {
        $bmi = $mass/($height*$height);
        return $bmi;
      } 
      if ($bmi <= 18.5) {
        $output = "UNDERWEIGHT";
      } else if ($bmi > 18.5 AND $bmi<=24.9 ) {
        $output = "NORMAL WEIGHT";
      } else if ($bmi > 24.9 AND $num<=29.9) {
        $output = "OVERWEIGHT";
      } else if ($bmi > 30.0) {
        $output = "OBESE";
      }
    }
    echo "Your BMI value is  " . bmi($mass,$height). "  and you are : "; 
    echo "$output";
    ?>
    

您需要在if子句之前使用函数:

if ($_GET['submit']) { 
    $mass = $_GET['mass'];
    $height = $_GET['height'];
    function bmi($mass,$height) {
        $bmi = $mass/($height*$height);
        return $bmi;
    }   
    $bmi = bmi($mass,$height); //<--- this is critical
    if ($bmi <= 18.5) {
        $output = "UNDERWEIGHT";
        } else if ($bmi > 18.5 AND $bmi<=24.9 ) {
        $output = "NORMAL WEIGHT";
        } else if ($bmi > 24.9 AND $bmi<=29.9) {
        $output = "OVERWEIGHT";
        } else if ($bmi > 30.0) {
        $output = "OBESE";
    }
    echo "Your BMI value is  " . $bmi . "  and you are : "; 
    echo "$output";
}
  1. 您的$输出始终相同,因为您的IF语句永远不会运行。U必须在IF语句之前设置$bmi变量的某个值,这样就可以添加IF语句之前的$bmi = bmi($mass, $height),然后在echo命令中调用bmi函数,您可以使用$bmi变量
<?php
if ($_GET['submit']) { 
    $mass = $_GET['mass'];
    $height = $_GET['height'];
    $height2 = ($height*$height);
    $bmi = $mass/$height2; //<--- this is critical
    if ($bmi <= 18.5) {
        $output = "UNDERWEIGHT";
        } else if ($bmi > 18.5 AND $bmi<=24.9 ) {
        $output = "NORMAL WEIGHT";
        } else if ($bmi > 24.9 AND $bmi<=29.9) {
        $output = "OVERWEIGHT";
        } else if ($bmi > 30.0) {
        $output = "OBESE";
    }
    echo "Your BMI value is  " . $bmi . "  and you are : "; 
    echo "$output";
}
?>