Degrees To Radians To Degrees
May 5, 2015
I saw this question on a beginning programmer’s forum a couple of weeks ago. There were several answers, some of them wrong. So we’ll do it right:
Given an angle expressed in degrees, minutes, and seconds, convert it to radians. Given an angle in radians, convert it to degrees, minutes and seconds.
Your task is to write programs that perform the two conversions. When you are finished, you are welcome to read or run a suggested solution, or to post your own solution or discuss the exercise in the comments below.
Trickier than it looks: in your solution, the use of round can result in a 60 in the seconds count for eg. 0.82234 radians (not the mention the problem of negative inputs).
Two solutions, this one seems more elegant: multiply out to the smallest quantity, round and then divide back out:
or (this is probably more efficient), do as your solution, but check for seconds overflow and adjust accordingly:
One slight residual doubt about this is if the minutes can overflow as well: if x < 1, then is k*x < k? – clearly mathematically true, but maybe the rounding of the multiplication can make the result be exactly k. Seems to work for 60 (60*nextafter(1,0) < 60 anyway) but can't see how to prove it.