Tuesday, June 11, 2013

C++ Program to Convert Rectangular to Polar Coordinates

To start with this program you must understand definitions of Rectangular and Polar coordinates. Rectangular coordinates are x and y position on a Cartesian coordinate system. To calculate Polar coordinates from Rectangular coordinates you have the calculate the distance from the Origin, r, and the angle from the x-axis, θ, specified by the point. To Understand better, I have drawn an image:
We need to know x and y on a Cartesian coordinate system to calculate the Polar coordinates, r and θ. We can use the following formulas:
r = √ (x^2 + y^2)
θ = arctan (y/x) where x != 0

C Plus Plus Program to Convert Rectangular to Polar Coordinates

 #include <iostream>
using namespace std;

void getcoord(double &, double &);
void polar(double,double,double &,double &);
void showcoord(double,double,double,double);

int main ()
{
    double x, y, distance, angle;
    getcoord(x,y); // Obtain (X,Y) Coordinates
    polar(x,y,distance,angle); // Convert Coodinates
    showcoord(x,y,distance,angle); // Show Polar Coordinates
    system("pause");
}

void getcoord(double &x, double &y)
{
    cout<<"Enter X  Value: ";
    cin>>x;
    cout<<"Enter Y Value: ";
    cin>>y;
    while(x < 1)
        cin>>x;
    cout<<"Your Coordinate: (" <<x <<", " <<y <<")" <<endl;
    return;
}

void polar(double x, double y, double &distance, double &angle)
{
    const double ToDegress = 180.0/3.141593; // Defined to convert Radians to Degrees

    distance = sqrt(x*x + y*y);
    angle = atan(y/x) * ToDegress;
    return;
}

void showcoord(double x, double y, double distance, double angle)
{
    cout<<"r: " <<distance <<endl;
    cout<<"Theta: " <<angle <<endl;
    return;
}
Any Questions, Please Comments.


6 comments:

  1. That looks WAYYYY more complex then needed. Check out cplusplus.com There are a few programs for this that I've found. That could help you simplify it :)

    ReplyDelete
  2. thank u for your helping
    i am a senior student at faculty of science
    my project for graduation is a big complex number class in c++
    i am studying computer science
    and i wanna your helping in my project
    can u help me ??

    ReplyDelete
    Replies
    1. this is my account in facebook
      https://www.facebook.com/mostafa.gamal.395
      my mail mostafasasa298@gmail.com

      Delete
  3. hello, great article but when i attempt to run the script it says neither sqrt or atan is defined in the scope? how do i define them?
    thanks.

    ReplyDelete
  4. You need to make sure you included cmath in thye libary i.e. #include

    ReplyDelete