Angle conversions

ddanbe 0 Tallied Votes 342 Views Share

If you have to convert an angle from degrees to radians and way back, here are some utility functions in C#, along with a program to test them.
I made use of the "out" keyword here, which allows a function to return more than one value. An alternative would be to return a struct containing all the values.
Any language out there which can do this?

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Mynamespace
{
    class Program
    {
	static void Main(string[] args)
        {
            int d, m, s;
            //angle is 18° 31' 27''
            double dd = AngleToDecimalDegrees(18, 31, 27);
            
            DecimalDegreesToAngle(dd, out d, out m, out s);
            Console.WriteLine("Decimal degrees for 18° 31' 27'' = {0}",dd);
            Console.WriteLine("This is : {0} d, {1} m, {2} s",d,m,s);
            Console.WriteLine("This is in radians : {0}", ToRadians(dd));
            Console.WriteLine("Or back to decimal degrees : {0}", ToDegrees(ToRadians(dd)));
            Console.ReadKey();
        }
        
        public static double AngleToDecimalDegrees(int d, int m, int s)
        {
            return (s / 60.0 + m) / 60.0 + d;
        }

        public static void DecimalDegreesToAngle(double ddeg, out int d, out int m, out int s)
        {
            d = (int)Math.Truncate(ddeg);
            double min = (ddeg - Math.Truncate(ddeg)) * 60.0;
            m = (int)Math.Round(min);
            double sec = (min - Math.Truncate(min)) * 60.0;
            s = (int)Math.Round(sec);
        }
        
        public static double ToRadians(double degrees)
        {
	    return degrees*Math.PI/180.0;
	}
		
	public static double ToDegrees(double radians)
	{
	    return radians*180.0/Math.PI;
	}
    }
}