此問題給定一個數字和百分比值,需求該數字的百分比。本文將學習如何用 PHP 以不同方法計算數字百分比。
理解公式
求數字百分比使用公式:(數字 × 百分比) / 100
範例:300 的 40% 計算為 (300 × 40) / 100 = 120。
數字:300 百分比:40% 結果:(300 × 40) ÷ 100 = 120
直接計算法
這是直接用基本乘除運算子計算數字百分比的方法
語法
$result = ($number * $percentage) / 100;
範例
<?php $number = 500; $percentage = 10; $result = ($number * $percentage) / 100; echo "The percentage value is: " . $result; ?>
The percentage value is: 50
使用函式
此方法建立可重複使用的函式,接收數字和百分比參數並回傳計算結果
<?php function findPercentage($num, $percent) { return ($num * $percent) / 100; } $number = 600; $percentage = 25; $result = findPercentage($number, $percentage); echo "The percentage value is: " . $result; ?>
The percentage value is: 150
使用物件導向方法
將百分比計算邏輯封裝在類別中,以利組織和重複使用
<?php class PercentageCalculator { public function calculatePercentage($num, $percent) { return ($num * $percent) / 100; } } $calculator = new PercentageCalculator(); $number = 700; $percentage = 30; $result = $calculator->calculatePercentage($number, $percentage); echo "The percentage value is: " . $result; ?>
The percentage value is: 210
方法比較
| 方法 | 最佳使用情境 | 時間複雜度 |
|---|---|---|
| 直接計算 | 簡單一次性計算 | O(1) |
| 函式 | 可重複使用的計算 | O(1) |
| 類別方法 | 物件導向的複雜應用 | O(1) |
結論
三種方法都能以 O(1) 時間複雜度高效計算 PHP 百分比。簡單計算用直接法、重複使用用函式、物件導向應用用類別。
