Convert numbers within a range to numbers within another range [duplicate]

拜拜、爱过 提交于 2019-12-03 19:13:33

问题


Possible Duplicate:
Convert a number range to another range, maintaining ratio

So I have a function that returns values within 0 and 255 and I need to convert these values to something between -255 and 255 So 200 would be roughly 145, 150 would be roughly 45 and so on.. I have looked at Convert a number range to another range, maintaining ratio but the formulas there won't work. Any other formula I could use?


回答1:


Try this:

int Adjust( int num )
{
    return num * 2 - 255;
}



回答2:


public static int ConvertRange(
    int originalStart, int originalEnd, // original range
    int newStart, int newEnd, // desired range
    int value) // value to convert
{
    double scale = (double)(newEnd - newStart) / (originalEnd - originalStart);
    return (int)(newStart + ((value - originalStart) * scale));
}



回答3:


General solution for arbitrary range...

var val1 = 200;
var min1 = 0;
var max1 = 255;
var range1 = max1 - min1;

var min2 = -255;
var max2 = 255;
var range2 = max2 - min2;

var val2 = val1*range2/range1 + min2;



回答4:


public int ConvertRange(
           int originalStart, int originalEnd,
           int newStart, int newEnd,
           int value)
{

  int originalDiff = originalEnd - originalStart;
  int newDiff = newEnd - newStart;
  int ratio = newDiff / originalDiff;
  int newProduct = value * ratio;
  int finalValue = newProduct + newStart;
  return finalValue; 

}



回答5:


Adjusted = original / 255 * 510 - 255

145 = 200 / 255 * 510 - 255
 45 = 145 / 255 * 510 - 255


来源:https://stackoverflow.com/questions/4229662/convert-numbers-within-a-range-to-numbers-within-another-range

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!