《编程思维与实践》1019.极坐标排序
题目
思路
直角坐标 ( x , y ) (x,y) (x,y)转极坐标 ( ρ , θ ) (\rho,\theta) (ρ,θ)公式: ρ = a 2 + b 2 , θ = a r t a n y x ( 0 < θ < π 2 ) \rho=\sqrt{a^2+b^2},\theta=artan\frac{y}{x}(0<\theta<\frac{\pi}{2}) ρ=a2+b2,θ=artanxy(0<θ<2π)
由于分母不能为0,所以还需要将x=0的情况单独分类考虑.
注意到反正切函数的值域是 ( − π 2 , π 2 ) (-\frac{\pi}{2},\frac{\pi}{2}) (−2π,2π), 但极坐标中的 θ \theta θ 范围是 ( 0 , 2 π ) (0,2\pi) (0,2π) ,所以需要进行一些简单的变形:
当 π 2 < θ < π \frac{\pi}{2}<\theta<\pi 2π<θ<π 时, y x < 0 , a r t a n y x < 0 , θ − π = a r t a n y x , \frac{y}{x}<0,artan\frac{y}{x}<0,\theta-\pi=artan\frac{y}{x}, xy<0,artanxy<0,θ−π=artanxy,
当 π < θ < 3 π 2 \pi<\theta<\frac{3\pi}{2} π<θ<23π 时, y x > 0 , a r t a n y x > 0 , θ − π = a r t a n y x , \frac{y}{x}>0,artan\frac{y}{x}>0,\theta-\pi=artan\frac{y}{x}, xy>0,artanxy>0,θ−π=artanxy,
当 3 π 2 < θ < 2 π \frac{3\pi}{2}<\theta<2\pi 23π<θ<2π 时, y x < 0 , a r t a n y x < 0 , θ − 2 π = a r t a n y x . \frac{y}{x}<0,artan\frac{y}{x}<0,\theta-2\pi=artan\frac{y}{x}. xy<0,artanxy<0,θ−2π=artanxy.
反正切值的计算可以直接调用<math.h>头文件中的atan函数,求根号可以调用sqrt函数.
代码
#include<stdio.h>
#include<math.h>
#include<stdlib.h>
#define pi 3.1415926 //宏定义
typedef struct{double x;double y;double r;double angle;}Point;
int cmp(const void*a,const void *b) //比较函数
{
Point *m=(Point*)a;
Point *n=(Point*)b;
if(m->angle!=n->angle)
{
if(m->angle>n->angle) //浮点数不能直接作差返回
{
return 1;
}
else{
return -1;
}
}
else{
if(m->r>n->r)
{
return -1;
}
else{
return 1;
}
}
}
int main()
{
int T;
scanf("%d",&T);
for(int i=0;i<T;i++)
{
int N;
scanf("%d",&N);
Point p[N];
for(int j=0;j<N;j++)
{
scanf("%lf %lf",&p[j].x,&p[j].y);
p[j].r=sqrt(p[j].x*p[j].x+p[j].y*p[j].y);
if(p[j].x>0&&p[j].y>=0) //第一象限
{
p[j].angle=atan(p[j].y/p[j].x);
}
else if(p[j].x<0&&p[j].y>=0) //第二象限
{
p[j].angle=pi+atan(p[j].y/p[j].x);;
}
else if(p[j].x<0&&p[j].y<0) //第三象限
{
p[j].angle=pi+atan(p[j].y/p[j].x);;
}
else if(p[j].x>0&&p[j].y<0) //第四象限
{
p[j].angle=2*pi+atan(p[j].y/p[j].x);;
}
else if(p[j].x==0&&p[j].y==0)
{
p[j].angle=0;
}
else if(p[j].x==0&&p[j].y>0)
{
p[j].angle=pi/2;
}
else if(p[j].x==0&&p[j].y<0)
{
p[j].angle=3*pi/2;
}
}
qsort(p,N,sizeof(Point),cmp);
printf("case #%d:\n",i);
for(int j=0;j<N;j++)
{
printf("(%.4lf,%.4lf)\n",p[j].r,p[j].angle);
}
}
return 0;
}