PHP编码帮助计算器

时间:2012-03-10 04:12:54

标签: php post

我很新,我需要PHP的帮助,我正在做一个BMI计算器,通过询问体重和身高以及优先测量系统(公制/英制)计算一个人的BMI,并评估用户的BMI(即BMI低于正常,正常,高于正常),现在我的问题是输出一直给我两个评估结果:(请参阅下面的img attch。)![见img here] [1 ]我不知道为什么它给了我两个“你的BMI高于正常水平”只有一个。请参阅链接以更好地了解我想说的内容:http://imgur.com/EHXQj

这是我的代码:

<?php

$weight = $_POST["txtWeight"];
$height = $_POST["txtHeight"];
$unit = $_POST["optUnit"];
$metric = ($weight / ($height * $height));
$imperial = (($weight * 703)/($height * $height));

if ($unit == "metric")
    echo "A height of $height Meters and a weight of $weight Kilograms = " .round($metric,1). " BMI.<br />";

         {
        if($metric <= 18.5)

            echo " Your BMI is below normal";

        else if ($metric >= 18.5 and $metric <= 24.9)

            echo " Your BMI is normal";

        else if($metric >= 25)

            echo " Your BMI is above normal";
        };

if ($unit == "imperial")
    echo "A height of $height Inches and a weight of $weight Pounds = " .round($imperial,1). " BMI.<br />";
        {
        if( $imperial <= 18.5)

            echo "Your BMI is below normal";

        else if ($imperial >= 18.5 and $imperial <= 24.9)

        echo "Your BMI is normal";

        else if($imperial >= 25)

            echo "Your BMI is above normal";
        };              

&GT;

2 个答案:

答案 0 :(得分:2)

您没有用括号括起if语句,因此大部分代码都在运行,而您并不期望这样做。

答案 1 :(得分:1)

我的猜测是你的括号错位了。试试这个:

<?php

$weight = $_POST["txtWeight"];
$height = $_POST["txtHeight"];
$unit = $_POST["optUnit"];
$metric = ($weight / ($height * $height));
$imperial = (($weight * 703)/($height * $height));

if ($unit == "metric") {
  echo "A height of $height Meters and a weight of $weight Kilograms = " . round($metric, 1) . " BMI.<br />";

  if ($metric <= 18.5) {
    echo "Your BMI is below normal";
  } else if ($imperial >= 18.5 && $imperial <= 24.9) {
    echo "Your BMI is normal";
  } else {
    echo "Your BMI is above normal";
  }
}

if ($unit == "imperial") {
  echo "A height of $height Inches and a weight of $weight Pounds = " . round($imperial, 1) . " BMI.<br />";

  if ($imperial <= 18.5) {
    echo "Your BMI is below normal";
  } else if ($imperial >= 18.5 && $imperial <= 24.9) {
    echo "Your BMI is normal";
  } else {
    echo "Your BMI is above normal";
  }
}          

?>

更好的方法是压缩重复的代码:

<?php

$weight = $_POST["txtWeight"];
$height = $_POST["txtHeight"];
$unit = $_POST["optUnit"];

if ($unit == "metric") {
  echo "A height of $height Meters and a weight of $weight Kilograms = " . round($metric, 1) . " BMI.<br />";
  $bmi = ($weight / ($height * $height));
} else if ($unit == "imperial") {
  echo "A height of $height Inches and a weight of $weight Pounds = " . round($imperial, 1) . " BMI.<br />";
  $bmi = (($weight * 703)/($height * $height));
}

if (isset($bmi)) {
  if ($bmi <= 18.5) {
    echo "Your BMI is below normal";
  } else if ($bmi >= 18.5 && $bmi <= 24.9) {
    echo "Your BMI is normal";
  } else {
    echo "Your BMI is above normal";
  }
}

?>