Convert numbers within a range to numbers within a

2019-02-04 21:15发布

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?

标签: c# math scaling
5条回答
老娘就宠你
2楼-- · 2019-02-04 21:22

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;
查看更多
爷、活的狠高调
3楼-- · 2019-02-04 21:27
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));
}
查看更多
我想做一个坏孩纸
4楼-- · 2019-02-04 21:35

Try this:

int Adjust( int num )
{
    return num * 2 - 255;
}
查看更多
萌系小妹纸
5楼-- · 2019-02-04 21:39

Adjusted = original / 255 * 510 - 255

145 = 200 / 255 * 510 - 255
 45 = 145 / 255 * 510 - 255
查看更多
该账号已被封号
6楼-- · 2019-02-04 21:40
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; 

}
查看更多
登录 后发表回答