Make Swift Assume Degrees for Trigonometry Calculations

后端 未结 7 2456
抹茶落季
抹茶落季 2020-12-06 14:01

Is it possible to change a setting, property, etc in Swift for iOS so that it assumes degrees for trigonometry calculations rather than radians?

For example si

7条回答
  •  难免孤独
    2020-12-06 14:22

    Seeing as I use trig a lot. I found the best way was to define some functions outside of the class ViewController.

    If you define them in any one of your .swift files just below the imports and just above the class ViewController:UIViewController { } then you can call them throughout the whole project.

    So for the sin function, I named it sindeg() standing for "sin degrees".

    func sindeg(degrees: Double) -> Double {
        return sin(degrees * M_PI / 180.0)
        }
    

    So this takes your degrees number converts it, solves it and returns as degrees. So all you need to do is type sindeg(45.5) and the result would = 0.71325045.

    Here is the others:

    func cosdeg(degrees: Double) -> Double {
        return cos(degrees * M_PI / 180.0)
    }
    func tandeg(degrees: Double) -> Double {
        return tan(degrees * M_PI / 180.0)
    }
    

    arcTan here is very similar, only difference is the return formula

     func atanDegree(degrees: Double) -> Double {
            return atan(degrees) * 180 / M_PI
        }
    

    This one is just to convert a radian value to degrees. Takes in radians, converts, returns back degrees.

    func Convert(radians: Double) -> Double {
        return radians * 180.0 / M_PI
    }
    

提交回复
热议问题