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.

Advertisement

Pages: 1 2

One Response to “Degrees To Radians To Degrees”

  1. matthew said

    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:

    void r2dms(float r, int &d, int &m, int &s)
    {
      int n = round(r*180*60*60/pi);
      s = n%60; n /= 60;
      m = n%60; n /= 60;
      d = n;
    }
    

    or (this is probably more efficient), do as your solution, but check for seconds overflow and adjust accordingly:

    void r2dms(float r, int &d, int &m, int &s)
    {
      r *= 180/pi;
      d = floor(r);
      r = (r-d)*60;
      m = floor(r);
      r = (r-m)*60;
      s = round(r);
      if (s == 60) {
        s = 0; m++;
        if (m == 60) {
          d = 0; d++;
        }
      }
    }
    

    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.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: