2013-05-08 57 views
1

我有一个0到359(即指南针)的输入。设置零点,如果该值低于或高于此值,则显示为-value或+值

我想设置一个零点,如果该值低于或高于此值,则显示为-value或+值。

实施例:

Zero Point: 2 
Input: 340 => Output: -22 
Input: 22 => Output: 20 

Zero Point: 40 
Input: 30 => Output: -10 
Input: 50 => Output: 10 

所以不管其中罗盘 '是',则输出总是相对于零点。

PS:甚至更短:如何将0-> 359的重复序列转换为线性序列,我可以像使用正常数字线一样工作?因此,如果359达到2次向上计数,该函数告诉我它是720(我可能错过了1°或2°的正确值)而不是359?

+2

你有什么试过?还有没有足够的信息来帮助所有..设置什么?你输出什么?你如何确定这些输入的输出? – Sayse 2013-05-08 06:55:21

+0

为什么340的输出是-22?正值和负值之间的边界在哪里?你是否尝试自己创建这种方法?粘贴你的代码。 – filipko 2013-05-08 07:02:59

+0

@filipko边界是零点。 – 2013-05-08 07:04:04

回答

2

假设你想要的输出从-179到180和的零点可从0到359

int output(int deg, int zeropoint) 
    { 
     var relative = deg - zeropoint; 
     if (relative > 180) 
      relative -= 360; 
     else if (relative < -179) 
      relative += 360; 
     return relative; 
    } 
+0

你应该改变你的答案,使用'else'而不是'else if',否则+1 – Sayse 2013-05-08 07:28:49

+0

否 - 如果相对值已经在预期的范围内,应该没有标准化(既不加也不减360) – lisp 2013-05-08 07:37:51

+0

啊对不起错过了那一点 - 还没醒过来! – Sayse 2013-05-08 07:56:44

0
int result = input - zero > 180 ? input - zero - 360 : input - zero; 
2

我觉得这样做你问什么,但我不相信您的要求。基本上,给定一个特定大小的“时钟”,从相对距离和输入值中获得一个点,它将找到到'时钟'上的点的最小距离,既可以是负值也可以是正值。

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; 
     } 
    } 
相关问题