Write procedures using c++ for converting between rectangular and polar coordinates named xy2polar and polar2xy. Invoking xy2polar(x,y,r,t) should take the rectangular coordinates (x,y) and save the resulting polar coordinates; (r,theta) are r and t, respectively. The procedure polar2xy(r,t,x,y) should have the reverse effect.
Be sure to handle the origin in a sensible manner.
It is useful to explore the following C++ procedures, which are housed in the cmath header file:
Variants of the absolute value function
int abs(int x)
long labs(long x)
double fabs(double x)
Other interesting/needed procedures
sin
cos
tan
asin
acos
atan
ceil
floor
hypot: Computes the hypotenuse of triangle with legs x and y
sqrt
My intention is for you to use intuition to determine what these procedures do. However, you may either write a quick main() procedure to check, ask the instructor, or even Google them.
// C++ program to convert from polar to rectangular and vice versa
#include <iostream>
#include <cmath>
using namespace std;
// function declaration
void xy2polar(double x, double y, double &r, double &t);
void polar2xy(double r, double t, double &x, double &y);
int main() {
double x,y,r,t;
cout<<"Enter x and y (with space): ";
cin>>x>>y;
xy2polar(x,y,r,t);
cout<<"Radius : "<<r<<" Theta : "<<t<<" radians"<<endl;
cout<<"Enter radius and theta (with space) : ";
cin>>r>>t;
polar2xy(r,t,x,y);
cout<<"X : "<<x<<" Y : "<<y<<endl;
return 0;
}
// function to convert rectangular coordinates to polar form
void xy2polar(double x, double y, double &r, double &t)
{
r = (sqrt(x*x + y*y));
if(x == 0 && y == 0)
t = 0;
else
{
t = atan(y/x);
// if point is in Quadrant 2 or 3 add 180 degrees
if((x<0 && y>=0) || (x < 0 && y < 0))
t += atan(1)*4;
// if point is in Quadrant 4 add 360 degrees
else if(x >= 0 && y<0)
t += atan(1)*8;
}
}
// function to convert polar form to rectangular coordinate
void polar2xy(double r, double t, double &x, double &y)
{
x = r*cos(t);
y = r*sin(t);
}
//end of program
Output:
Get Answers For Free
Most questions answered within 1 hours.