我从极坐标到笛卡尔坐标的转换不正确,反之亦然。我的代码会产生奇怪的点,例如 (1,-0)。我使用这个计算器来检查我的转换。当我转换回笛卡尔坐标时,其中一种转换也是完全错误的。
b点:(0,1) => (1,1.5708) => (0,0)
#include <math.h>
#include <iostream>
/* Title: Polar - Cartesian Coordinate Conversion
* References: HackerRank > All Domains > Mathematics > Geometry > Polar Angles
* Cartesian to Polar: (radius = sqrt(x^2 + y^2), theta = atan(y/x))
* Polar to Cartesian: (x = radius*cos(theta), y = radius*sin(theta))
*/
//General 2D coordinate pair
struct point{
point(float a_val, float b_val) : a(a_val), b(b_val){;};
point(void){;};
float a, b;
};
//Converts 2D Cartesian coordinates to 2D Polar coordinates
point to_polar(/*const*/ point& p){//*** Conversion of origin result in (r, -nan) ***
point ans(sqrt(pow(p.a,2) + pow(p.b,2)), atan(p.b/p.a));
return ans;
}
//Converts 2D Polar coordinates to 2D Cartesian coordinates
point to_cartesian(/*const*/ point& p){
point ans(p.a * cos(p.b), p.a * sin(p.b));
return ans;
}
//Outputs 2D coordinate pair
std::ostream& operator<<(std::ostream& stream, const point& p){
stream << "(" << p.a << "," << p.b << ")";
return stream;
}
int main(){
//Test Points - Cartesian
point a(0, 0);
point b(0, 1);
point c(1, 0);
point d(0,-1);
point e(-1,0);
//Print Cartesian/Rectangular points
std::cout << "Cartesian Coordinates:" << std::endl;
std::cout << a << std::endl;
std::cout << b << std::endl;
std::cout << c << std::endl;
std::cout << d << std::endl;
std::cout << e << std::endl;
//Print Cartesian to Polar
std::cout << "Polar Coordinates:" << std::endl;
std::cout << to_polar(a) << std::endl;//Failure (0,-nan)
std::cout << to_polar(b) << std::endl;//Success
std::cout << to_polar(c) << std::endl;//Success
std::cout << to_polar(d) << std::endl;//Success
std::cout << to_polar(e) << std::endl;//Failure (1,-0)
//Print Polar to Cartesian
std::cout << "Cartesian Coordinates:" << std::endl;
std::cout << to_cartesian(a) << std::endl;//Success
std::cout << to_cartesian(b) << std::endl;//Failure (0,0)
std::cout << to_cartesian(c) << std::endl;//Success
std::cout << to_cartesian(d) << std::endl;//Failure (0,-0)
std::cout << to_cartesian(e) << std::endl;//Failure (-1,-0)
return 0;
}