我正在尝试使用引用在笛卡尔和极坐标之间进行转换来制作一个简单的转换器,问题是它给了我错误的答案,有时是0,0。我想知道有什么问题以及如何解决。 这是代码:
#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;
}
答案 0 :(得分:1)
这两个函数的结果都应该是浮点数,而不是整数:
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);
}
您正在计算的值是正确的,但随后将结果转换为整数。转换为int时会被截断,即0.1
和0.9
都变成0
。
您在从极点到直角坐标的转换中也有错别字。使用了错误的变量。正确的是:
polarToCartesian(rr, qq, xx, yy);
在@Yunnosch注释之后,您应该使用atan2()
而不是atan()
。可以找到详细的说明here