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.
If you want exactly: "π/2", I don't think this is possible with double. You might get this in String, but not in a number. I think your best option would be to take an optional bool in which case result is returned as multiple of pi.
degreesToRadians(90, resultAsMultipleOfPi:true)
If this bool is true then 0.5 should be returned. You may need to do some rounding off to get well rounded numbers.
If you look closely on what is really M_PI
you will see that it is predefined double value in math.h that equals
#define M_PI 3.14159265358979323846264338327950288 /* pi */
If you want more precision you can declare and use long double value instead.
To represent 90
degrees as π/2
, what you want to do is
consider the fraction of degrees
over 180 (ie numerator of degrees
and denominator of 180
);
reduce this fraction (ie 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, ie 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.
You can directly use M_PI constant.
If you need in float format just use this,
let pi = Float(M_PI)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.