2011-10-23 199 views
0

我遇到的問題不是找到距離,而是使用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 

回答

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參數才能傳遞給方法的值,已修改,然後需要傳回給調用者。

+1

問題解決謝謝我使用180/2 * Math.PI而不是180/Math.PI – Jordan

+0

要將Atan2結果從-180 ... 180轉換爲0 ... 360,您只需要移動180,而不是360. 360度的轉變會給你180 ... 540的範圍。您只需要移動180度: q =(Math.Atan2(y,x)* 180.0/Math.PI + 180.0); (使用180.0 vs 180來消除任何可能的轉換開銷)。 –

+0

@RichardRobertson不,事實並非如此。確實,加180會讓你的值在正確的範圍內,但這些值是錯誤的值。您需要按照我所說的去做,將360添加到任何負值。你只能改變負值,你必須改變它們,否則你會改變它的值。請記住,圍繞一個圓的角度進行比較的模數相等爲360。 –