将矩形点转换为极坐标

时间:2011-10-23 19:47:16

标签: c#

我遇到的问题是没有找到距离,而是用Atan()找到弧度并将其转换为度数。

using System;
class Program
{
    static void Main()
    {
        double xCoord =0, yCoord=0 ;       
        //accessing methods
        getUserInput(ref xCoord, ref yCoord);
        CalulatePolarCoords(ref xCoord, ref yCoord);
        outputCords( ref xCoord,  ref yCoord);
        Console.ReadLine();
    }//End Main()

    static void getUserInput(ref double xc, ref double yc) 
    {
    //validating input
        do
        {
            Console.WriteLine(" please enter the x cororidnate must not equal 0 ");
            xc = double.Parse(Console.ReadLine());
            Console.WriteLine("please inter the y coordinate");
            yc = double.Parse(Console.ReadLine());
        if(xc <= 0)
    Console.WriteLine(" invalid input"); 
        }
        while (xc <= 0);
            Console.WriteLine(" thank you");

    }

   //calculating coords
    static void CalulatePolarCoords(ref double x , ref double y) 
    {
        double r;
        double q;
       r = x;
       q = y;
        r = Math.Sqrt((x*x) + (y*y));

        q = Math.Atan(x/y);

    x = r;
    y = q;
    }
    static void outputCords( ref double x, ref double y)
    {
        Console.WriteLine(" The polar cordinates are...");
        Console.WriteLine("distance from the Origin {0}",x);
        Console.WriteLine(" Angle (in degrees) {0}",y);
        Console.WriteLine(" press enter to continute");

    }
}//End class Program

1 个答案:

答案 0 :(得分:4)

您想在此处使用Atan2

q = Math.Atan2(y, x);

转换为度数乘以180/Math.PI

这将给出-180到180范围内的结果。如果你想要它在0到360的范围内,你将不得不将任何负角度移动360.

我还强烈建议您不要使用与以往笛卡尔坐标相同的参数返回极坐标。让你的功能像这样:

static void CalculatePolarCoords(double x, double y, out double r, out double q)

您的outputCoords方法也错误地使用了ref个参数。仅对传递给方法的值使用ref参数进行修改,然后需要将其传递回调用方。