user2252471 - 1 year ago 88

Swift Question

I am trying to build a degrees/radians calculator. Here are the functions I have.

`func degreesToRadians(degrees: Double) -> Double {`

return degrees * (M_PI / 180)

}

func radiansToDegrees(radians: Double) -> Double {

return radians * (180 / M_PI)

}

degreesToRadians(90)

radiansToDegrees(M_PI/4)

degreesToRadians(90) returns 1.5707963267949

radiansToDegrees(M_PI/4) returns 45.0

What I want to happen is in the Degrees to Radians function instead of 1.5707963267949 I want the output to be π/2. Is this even possible?

Thanks.

Recommended for you: Get network issues from **WhatsUp Gold**. **Not end users.**

Answer Source

To represent `90`

degrees as `π/2`

, what you want to do is

consider the fraction of

`degrees`

over 180 (i.e. numerator of`degrees`

and denominator of`180`

);reduce this fraction (i.e. divide both the numerator and denominator by the greatest common factor); in the case of

`90/180`

, the greatest common factor is, in fact,`90`

, yielding a reduced numerator of`1`

and a reduced denominator of`2`

;the result as a string representation of the fraction, i.e. something like

`"\(reducedNumerator)π/\(reducedDenominator)"`

Obviously, if either the numerator or denominator are

`1`

, then you can suppress that portion of the string, but hopefully you get the basic idea.

Take a crack at that.

Recommended from our users: **Dynamic Network Monitoring from WhatsUp Gold from IPSwitch**. ** Free Download**