2014-03-19 39 views
0

我有一個從「min」到「max」的給定範圍。 min表示爲100%,max表示爲0%。平均值(min + max)/ 2表示爲50%。如何在java中給定範圍內找到百分比

我將給出的輸入是在[min,max]範圍內的值「x」,並且輸出應該是對應於所提供輸入的百分比。

例如,考慮比範圍爲[100,300]

if x=100 then output=100% 
if x=300 then output=0% 
if x=200 then output=50% 
if x=150 then output=75% 
if x=250 then output=25% 

不管該範圍內提供x的值[最小值,最大值]相應的百分比應計算。

我已經嘗試了各種邏輯,但我似乎無法得到這個問題的正確公式。

+6

這個問題似乎是題外話,因爲它是關於獲得這個問題的解決方案。這可能是在http://math.stackexchange.com主題 – devnull

+2

減去最小的值和最大值,並計算perctange正常... – MadProgrammer

+0

@devnull好吧我會檢查..謝謝你:) – Mano

回答

4

如果開始和結束是變量來存儲值,則

1)你可以只從0開始的限制結束啓動 和值傳遞值 - 啓動 2)計算百分比 3)返回100 -percentage

public static void main(String[] args) { 

    System.out.println(find_percent(100,300,100)+"%"); 
    System.out.println(find_percent(100,300,300)+"%"); 
    System.out.println(find_percent(100,300,200)+"%"); 
    System.out.println(find_percent(100,300,150)+"%"); 
    System.out.println(find_percent(100,300,250)+"%"); 
    System.out.println(""); 
    System.out.println(find_percent(20,40,20)+"%"); 
    System.out.println(find_percent(20,40,40)+"%"); 
    System.out.println(find_percent(20,40,25)+"%"); 
    System.out.println(find_percent(20,40,35)+"%"); 

} 


public static double find_percent(double start,double end,double val){ 

    end = end- start; 
    val = val - start; 
    start = 0; 

    return((1-(val/end))*100); 
} 

輸出:

100.0% 
0.0% 
50.0% 
75.0% 
25.0% 

100.0% 
0.0% 
75.0% 
25.0% 
+1

這就是工作完美兄弟:)非常感謝你。我已經嘗試了所有可能的範圍和輸入值的「X」其工作良好.. – Mano

0

在Java中,對應的分配將是

double percentage = 1.0f - Math.Abs(x-min)/Math.Abs(max-min); 

其中絕對函數用於覆蓋maxmin是不同符號的情況下。

+0

但如果我給這裏的值x = 200在範圍[100,300]結果是100%。實際上它應該是50%.. – Mano

+0

如果'x = 200','min = 100'和'max = 300'的值插入到上面的表達式中,評估結果爲(x-min)/(max-min )=(200-100)/(300-100)= 100/200 = 50%'這是期望的結果。 – Codor

+0

嗯,我看到..我很好,那麼我將能夠使用它也:) – Mano