Reputation: 740
Im trying to make a simple converter using reference to convert between cartesian and polar the problem is it gives me wrong answers and sometimes 0 ,0 . I want to know what's the problem and how can i fix it . this is the code :
#include <iostream>
#include <cmath>
using namespace std;
void cartesianToPolar(int x,int y,float &r,float &q ) {
r = sqrt(x * x + y * y); q = atan(y / x);
}
void polarToCartesian(float r, float q, int &x, int &y) {
x = r * cos(q); y = r * sin(q);
}
int main() {
int cevap ;
int x = 0 , y = 0 ,xx = 0 , yy = 0;
float r = 0 , q = 0 , rr = 0 , qq = 0 ;
cout << "Choose please....." << endl;
cout << "1-Cartesian -> polar "<<endl;
cout << "2-polar ->Cartesian " << endl;
cin >> cevap;
if(cevap==1){
cout << "enter x value: " ;
cin >> x;
cout << "enter y value: " ;
cin >> y;
cartesianToPolar(x,y,rr,qq);
cout << "r: " << rr << " " << "Q: " << qq << endl;
}
else if (cevap==2)
{
cout << "enter r value : ";
cin >> rr;
cout << "enter Q value: ";
cin >> qq;
polarToCartesian(r, q, xx, yy);
cout << "x: " << xx << " " << "y: " << yy << endl;
}
return 0;
}
Upvotes: 0
Views: 4285
Reputation: 4744
Results of both of your functions should be floats, not ints:
void cartesianToPolar(float x, float y, float &r, float &q ) {
r = sqrt(x * x + y * y); q = atan(y / x);
}
void polarToCartesian(float r, float q, float &x, float &y) {
x = r * cos(q); y = r * sin(q);
}
The values you were computing were correct, but the result was converted to integers afterwards. Conversion to int happens by trunctation, that is, 0.1
and 0.9
all become just 0
.
You also had a typo in your polar to cartesian conversion in the main. Used the wrong variable. Correct is:
polarToCartesian(rr, qq, xx, yy);
Following @Yunnosch comment, you should use atan2()
rather than atan()
. Detailed explanation can be found here
Upvotes: 2