問題描述
使用百分比查找範圍內的值 (find the value within a range using percent)
我有一個數字範圍 40 到 255
,其中 40 是 0%,255 是 100% 我怎樣才能得到 50% 的數字?
我嘗試搜索尋找一種方法來做到這一點,但找不到任何方法。
參考解法
方法 1:
- You have (255‑40) = 100%
- 1% = (255‑40)/100
- 50% = ((255‑40)/100) * 50 = 107.5
- Since you have offset of 40 at the beginning, 50% from offset = 107.5 + 40 = 147.5
</ul>
方法 2:
Extending @Kiran s answer with some generic Javascript
const rangeMin = 40;
const rangeMax = 255;
const percentage = 50;
const valueFromPercentage = (((rangeMax ‑ rangeMin) / 100) * percentage ) + rangeMin;
const rangeMin = 40;
const rangeMax = 255;
const value = 147;
const percentageFromValue = ((value ‑ rangeMin) / (rangeMax ‑ rangeMin)) * 100;
方法 3:
Any number c
in an interval [a, b]
can be written as a linear combination of the two endpoints c = a*x + b*(1‑x)
for some x ∈ [0, 1]
.
For [a, b] = [0, 100]
, the number c = 50
can be written as 0*0.5 + 100*0.5
so x = 0.5
.
If the interval [0, 100]
is linearly mapped to [40, 255]
, the ratio x = 0.5
will stay the same, and so c
gets mapped to c' = 40*0.5 + 255*0.5 = (40 + 255)/2 = 147.5
.
(by usupyusuke、Kiran、Pascal Lamers、dxiv)