Search code examples
c#distanceangle

Coding for Distance and angle in c#


I am working on my first program in C# and I'm having problems getting my equations for distance and angle to calculate. My purpose is to prompt for an X1,Y1 value, an X2, Y2 value, and calculate the distance and angle between the two points. I will paste my (very horrible) code below. Thanks in advance for any help!

        //prompt and store the x and y for two points
        Console.WriteLine("Please enter X1:");
        float point1X = float.Parse(Console.ReadLine());
        Console.WriteLine("Please enter Y1:");
        float point1Y = float.Parse(Console.ReadLine());
        Console.WriteLine("Please enter X2:");
        float point2X = float.Parse(Console.ReadLine());
        Console.WriteLine("Please enter Y2:");
        float point2Y = float.Parse(Console.ReadLine());
        Console.WriteLine("");

        //calculate the distance
        double deltaX= Math.Pow(point2X - point1X, 2);
        double deltaY= Math.Pow(point2Y - point1Y, 2);
        Console.WriteLine("double deltaX, double deltaY");
        Console.WriteLine("");

        //calculate the angle
        double angle = Math.Atan2(deltaX, deltaY);
        Console.WriteLine("double angle");
        Console.WriteLine("");

Solution

  • If this is something like this you searched for, this is Mathematics, not C# ;-) :

            //calculate the distance
            ...
            Console.WriteLine("Distance : " + Math.Sqrt(deltaX + deltaY));
    
            //calculate the angle
            double angle = Math.Atan2(point2Y - point1Y, point2X - point1X);
            ...
            Console.WriteLine(angle + " Rad");
            Console.WriteLine(angle * 180 / Math.PI + " Deg");