سؤال

I have a given range say from "min" to "max". The min is represented as 100% and max is represented as 0%. The average value (min+max)/2 is represented as 50%.

The input i will be giving is a value "x" within the range [min, max] and the output should be the percentage corresponding to the input provided.

For example, consider than range as [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%

Whatever the value of x provided within the range [min, max] the corresponding percentage should be calculated.

I have tried various logic but i cant seem to get the right formula for this problem.

هل كانت مفيدة؟

المحلول

if start and end are variables to store the values then

1) You could just start the limits with 0 to end-start and value passed value - start 2) Calculate Percentage 3) Return 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);
}

Output:

100.0%
0.0%
50.0%
75.0%
25.0%

100.0%
0.0%
75.0%
25.0%

نصائح أخرى

In Java, the corresponding assignment would be

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

where the absolute function is used to cover the case that max and min are of different sign.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top