比较角度和向上的奇怪行为

比较角度和向上的奇怪行为

本文介绍了比较角度和向上的奇怪行为的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个可比较角度的函数..如果从起始航向到-5/+ 5deg范围内的角度si,则应返回Color .green,否则应返回.orange.

i have a func to compare angles.. if the angles si between the range -5/+5deg from the starting heading this should return Color .green otherwise should return .orange.

我简化了项目,因此可以轻松地在快速的Playground中使用.

i simplify the project so it can be easy to use in swift Playground.

这是我的乐趣:

func convertToPositiveAngle(_ angle : Angle) -> Angle {
    var toRet = Angle(degrees: fmod(angle.degrees, 360))
    if toRet.degrees < 0 {
        toRet.degrees += 360.0;
    }
    return toRet
}


let headingStart = 3.0
let currentHeading = 3.0


func centro(startHeading:Double, currentHeading : Double)->Color {
    var coloreDaMostrare : Color = .black

    let HDGstart  = Angle(degrees: startHeading)
    let HDHCurrent = Angle(degrees: currentHeading)
    let rangeLower = convertToPositiveAngle(HDGstart - Angle(degrees: 5))
    let rangeUpper = (HDGstart + Angle(degrees:  5))


    if HDHCurrent.degrees>=rangeLower.degrees && HDHCurrent.degrees <= rangeUpper.degrees{
        coloreDaMostrare = .green
        debugPrint("1")
    } else if HDHCurrent.degrees > rangeUpper.degrees {
        debugPrint("2")
        coloreDaMostrare = .orange
    }else if HDHCurrent.degrees < rangeLower.degrees {
        debugPrint("3")
        coloreDaMostrare = .orange
    }

    return coloreDaMostrare
}


centro(startHeading: headingStart, currentHeading: currentHeading)

// should return green not orange

当起始航向接近360/0时出现问题...一个小值.

the problem appear the when the starting heading is close to 360/0... a small value..

如果使用例如hight值,则没问题,一切正常..

if you use for example hight value there is no problem,all working fine..

我做错了什么?

推荐答案

使用这种方法:直接玩度数.

Use this approach: Directly play with degrees.

func centro(startHeading:Double, currentHeading : Double)->Color {
    var coloreDaMostrare : Color = .black

    let HDGstart  = Angle(degrees: startHeading)
    let HDHCurrent = Angle(degrees: currentHeading)
    let finalAngle = convertToPositiveAngle(HDGstart)

    if ((finalAngle.degrees - 5)...(finalAngle.degrees + 5)).contains(HDHCurrent.degrees) {
        coloreDaMostrare = .green
        debugPrint("1")
    } else {
        debugPrint("2")
        coloreDaMostrare = .orange
    }
        /**
        //Or another option
        let lowerBound = finalAngle.degrees - 5
        let upperBound = finalAngle.degrees + 5
        let currentBound = HDHCurrent.degrees

        if lowerBound <= currentBound && currentBound <= upperBound {
            coloreDaMostrare = .green
            debugPrint("1")
        } else {
            debugPrint("2")
            coloreDaMostrare = .orange
        }
         */
    return coloreDaMostrare
}

这篇关于比较角度和向上的奇怪行为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-22 14:04