Reputation: 414
I have an input of 0 to 359 (ie a compass).
I want to set a zero point and if the value is lower or higher than this it is shown as -value or +value.
Example:
Zero Point: 2
Input: 340 => Output: -22
Input: 22 => Output: 20
or
Zero Point: 40
Input: 30 => Output: -10
Input: 50 => Output: 10
So no matter where the compass 'is', the output is always relative to the zero point.
PS: Or even shorter: How do I convert a repeating sequence of 0->359 into a linear sequence that I can work with like with a normal number line? So if 359 is reached 2 times counting upwards the function tells me it is at 720(I might've missed the right value here for 1° or 2°) and not 359?
Upvotes: 1
Views: 371
Reputation: 4198
Assuming you want an output from -179 to 180 and the zeropoint can be from 0 to 359
int output(int deg, int zeropoint)
{
var relative = deg - zeropoint;
if (relative > 180)
relative -= 360;
else if (relative < -179)
relative += 360;
return relative;
}
Upvotes: 2
Reputation: 27105
I think this does what you ask, but I'm not confident about your requirements. Basically, given a 'clock' of a certain size, a point to get the relative distance from and an input value, it will find the smallest distance to the point on the 'clock', either negative or positive.
static void Main(string[] args)
{
Console.WriteLine(getRelativeValue(2, 360, 340)); //-22
Console.WriteLine(getRelativeValue(2, 360, 22)); // 20
Console.WriteLine(getRelativeValue(2, 360, 178)); // 176
Console.Read();
}
static int getRelativeValue(int point, int upperBound, int value)
{
value %= upperBound;
int lowerBoundPoint = -(upperBound - value + point);
int upperBoundPoint = (value - point);
if (Math.Abs(lowerBoundPoint) > Math.Abs(upperBoundPoint))
{
return upperBoundPoint;
}
else
{
return lowerBoundPoint;
}
}
Upvotes: 2