两个值之间的百分比计算

时间:2013-08-15 13:27:33

标签: java android math

我想获得介于0.0和-0.5之间的结果。我有值:MIN = x,MAX = y和IN = x。值MIN应该导致-0.5%和MAX 0.0%的百分比。例如,如果MIN的值为240px,则MAX为600px,IN为360px,IN应为-0.33%的百分比。但我不知道如何进行这种计算。

P.S。:IN不能高于0.0或低于-0.5。 P.2.2:对不起我的英语。

我试过的代码,但没有用:

float percent = (((currentX / max) * min) / (max - min) * (-1)); Animation openNavigationDrawer = new TranslateAnimation( Animation.RELATIVE_TO_PARENT, percent, Animation.RELATIVE_TO_PARENT, 0.0f, Animation.RELATIVE_TO_PARENT, 0.0f, Animation.RELATIVE_TO_PARENT, 0.0f); openNavigationDrawer.setDuration(200); navigationDrawer.setAnimation(openNavigationDrawer);

第二个(工作,但不好):

float percent = -0.0f;
    float posDividerDefault = max / 12, 
    posDividerOne = min + posDividerDefault, posDividerTwo = posDividerOne + posDividerDefault, 
    posDividerThree = posDividerTwo + posDividerDefault, posDividerFour = posDividerThree + posDividerDefault, 
    posDividerFive = posDividerFour + posDividerDefault, posDividerSix = posDividerFive + posDividerDefault;

    if (currentX < posDividerOne) {
        percent = -0.5f;

    } else if (currentX > posDividerOne && currentX < posDividerTwo) {
        percent = -0.45f;

    } else if (currentX > posDividerTwo && currentX < posDividerThree) {
        percent = -0.4f;

    } else if (currentX > posDividerThree && currentX < posDividerFour) {
        percent = -0.3f;

    } else if (currentX > posDividerFour && currentX < posDividerFive) {
        percent = -0.2f;

    } else if (currentX > posDividerFive && currentX < posDividerSix) {
        percent = -0.1f;

    } else if (currentX > posDividerSix) {
        percent = -0.0f;

    }

2 个答案:

答案 0 :(得分:5)

根据你的描述,我想你想要的公式是:

result = -0.5 + 0.5*( (in - min) / (max - min) );

但是既然你没有展示任何代码也没有解释它的目的,那只是一个疯狂的猜测。

答案 1 :(得分:0)

与@MightyPork完全相同,但恕我直言会更清楚地说明发生了什么:

static final double MIN = -0.5;
static final double MAX = 0.0;
public void test(double x, double min, double max) {
  // (x - min)     = translate to min
  // / (max - min) = scale to unit
  // * (MAX - MIN) = scale to final
  // + MIN         = translate to MIN
  double v = (x - min) / (max - min) * (MAX - MIN) + MIN;
  System.out.println("test("+x+","+min+","+max+") = "+v);
}