Inconsistency with Math.Round()

后端 未结 3 807
孤独总比滥情好
孤独总比滥情好 2021-01-20 17:11

I have two functions that are intended to contain angles between (-180,180] and (-π,π]. The intent is that given any angle from -inf to +inf it will retain the equivalent an

3条回答
  •  陌清茗
    陌清茗 (楼主)
    2021-01-20 17:38

    It does not address the rounding issue, but here is how I would to what you want to do :

    private static double ConvertAngle(double angle)
    {
        bool isNegative = angle < 0;
        if (isNegative)
            angle *= -1;
    
        angle = angle % 360;
        if (isNegative)
            angle = -1 * angle + 360;
    
        if (angle > 180)
            angle = (angle - 360);
    
        return angle;
    }
    

    Note: This way supposes you want "behind" to be 180 degrees, not -180 degrees.

提交回复
热议问题