Program to convert polar coordinates to cartesion coordinates and vice versa and finding distance between two points in C++.

This is working code to convert cartesion coordinates to polar coordinates and vice versa, also find the distance between two points.

#include<iostream>
#include<math.h>
using namespace std;
class Rectangular
{
 float x,y,r,theta,d;
 public:
 void getdata()
 {
 cout<<"enter the cartesian coordinates:";
 cin>>x>>y;
 }
 void recttopolar();
 void distanceofcartesian();
};/*definition of class for cartesian coordinates*/
class Polar
{
 float x,y,r,theta,d;
 public:
 void getdata()
 {
 cout<<"enter the polar coordinates:";
 cin>>r>>theta;
 }
 void polartorect();
 void operator-(Polar);
};/*definition of class for polar coordinates*/
void Rectangular::recttopolar()
{
 Rectangular R1;
 R1.getdata();
 r=sqrt(R1.x*R1.x+R1.y*R1.y);
 if((x>=0&y>=0)||(x>=0&y<=0))
 {
 theta=atan(R1.y/R1.x);
 }
 if(x<0&y>0)
 {
 theta=3.14-atan(y/(-x));
 }
 if(x<0&y<0)
 {
 theta=atan((-y)/(-x))-3.14;
 }
 cout<<endl;
 cout<<"Polar coordinates are:"<<r<<" "<<theta<<endl;
}/*function to convert cartesian coordinates to polar coordinates*/
void Polar::polartorect()
{
 Polar P1;
 P1.getdata();
 x=P1.r*cos(P1.theta);
 y=P1.r*sin(P1.theta);
 cout<<endl;
 cout<<"rectangular coordinates are:"<<x<<" "<<y<<endl;
}/*function to convert polar coordinates to cartesian coordinates*/
void Rectangular::distanceofcartesian()
{
 Rectangular R1,R2;
 R1.getdata();
 R2.getdata();
 d=sqrt((R1.x-R2.x)*(R1.x-R2.x)+(R1.y-R2.y)*(R1.y-R2.y));
cout<<"distance:"<<d<<endl;
}/*function to find distance between cartesian coordinates*/
void Polar::operator-(Polar P2)
{
 d=sqrt(r*r+P2.r*P2.r-2*r*P2.r*cos(theta-P2.theta));
 cout<<"distance:"<<d<<endl;
}/*function to find distance between polar coordinates using operator overloading&*/
main()
{
 int n;
 //Rectangular R1,R2;
 //Polar P1,P2;
 cout<<"what is the operation to be performed"<<endl;
 cout<<"1.rect to polar"<<endl<<"2.polar to rect"<<endl<<"3.distance of cartesian"<<endl<<"4.distance of polar"<<endl;
 cin>>n;
 if(n==2)
 {
 Polar P1;
 P1.polartorect();
 }
 if(n==1)
 {
 Rectangular R1;
 R1.recttopolar();
 }
 if(n==3)
 {
 Rectangular R1;
 R1.distanceofcartesian();
 }
 if(n==4)
 {
 Polar P1,P2;
 P1.getdata();
 P2.getdata();
 P1-P2;
 }
}
Advertisements

One thought on “Program to convert polar coordinates to cartesion coordinates and vice versa and finding distance between two points in C++.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s