php - 以百分比计算值范围

标签 php algorithm math formula percentage

以下函数接受一个 DPI 值并返回一个百分比:

    100%        if the value is bigger than 200
    50% to 100% if the value is between 100 and 200
    25% to 50%  if the value is between 80 and 100
    0%  to 25%  if the value is lower than 80

    static public function interpretDPI($x) {
        if ($x >= 200) return 100;
        if ($x >= 100 && $x < 200) return 50 + 50 * (($x - 100) / 100);
        if ($x >= 80 && $x < 100) return 25 + 25 * (($x - 80) / 20);
        if ($x < 80) return 25 * ($x / 80);
    }

现在我必须根据这些规则更改此函数,返回:

    100%        if the value is bigger than 100
    75% to 100% if the value is between 72 and 100
    50% to 75%  if the value is between 50 and 72
    0%  to 50%  if the value is lower than 50

为了实现这一点,我尝试根据我对其行为的理解来重新建模该函数:

    static public function interpretDPI($x) {
        if ($x >= 100) return 100;
        if ($x >= 72 && $x < 100) return 75 + 75 * (($x - 72) / 28);
        if ($x >= 50 && $x < 72) return 50 + 50 * (($x - 50) / 22);
        if ($x < 50) return 25 * ($x / 50);
    }

但结果完全错误。例如,96 的 DPI 会给我 141%。显然这是错误的,但我缺乏数学理解来知道为什么 - 以及如何解决它。

我一定是误解了函数的工作原理。

谁能详细说明一下?

最佳答案

像这样编辑函数代码

 static public function interpretDPI($x) {
    if ($x > 100) return 100;
    if ($x > 72 && $x <= 100) return 75 + 75 * (($x - 72) / 28);
    if ($x >= 50 && $x <= 72) return 50 + 50 * (($x - 50) / 22);
    if ($x < 50) return 25 * ($x / 50);
 }

它会根据你的要求工作

关于php - 以百分比计算值范围,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16561404/

相关文章:

包含 "key : value"项的 php 搜索数组

c# - 在特定条件下使用 LINQ 从列表中获取数字

algorithm - 可以使用哪些算法或方法从图像中识别对象

python - 波动检验的MSS-最大似然法

algorithm - 以非常高的精度找到 2^(1/3) 的连分数

Java 旋转矩形产生奇怪的值

PHP 产品数据库中的三列表

从 Json 解码时的 PHP 未定义索引

php - Codeigniter - 设置 SSL 并收到 404 错误

java - Java 中二维 int 数组优化的洪水填充