天天看點

php運算百分比,如何使用php從表單輸入計算100%(百分比)

沒有必要讓事情不必要地進步。

如果這樣做的話,就把它留在那裡。

你有一個錯誤:

if($num1+$num2 < 0.1) {

echo "Error: less than 1%";

}僅當百分比小于0.1%而不是1%時才會顯示錯誤。

您應該将其更改為以下内容:

if($num1+$num2 < 1) {

echo "Error: less than 1%";

}在使代碼更易于閱讀方面,您可以将最小和最大百分比存儲在變量中。您還可以充分利用驗證。

有關示例,請參閱以下内容。

$minPercentage = 1;

$maxPercentage = 100;

if (! (isset($_POST['num1']) && is_numeric($_POST['num1']))) {

echo "Error: num1 should be numeric.";

} elseif (! (isset($_POST['num2']) && is_numeric($_POST['num2']))) {

echo "Error: num2 should be numeric.";

} else {

$num1 = $_POST['num1'];

$num2 = $_POST['num2'];

$totalPercentage = $num1 + $num2;

if ($totalPercentage < $minPercentage) {

echo "Error: less than {$minPercentage}%";

} elseif ($totalPercentage > $maxPercentage) {

echo "Error: more than {$maxPercentage}%";

} else {

echo "Total percentage is {$totalPercentage}%";

}

}