Convert numbers within a range to numbers within a

2019-02-04 20:51发布

问题:

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


标签: c# math scaling