《编程思维与实践》1019.极坐标排序

《编程思维与实践》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;
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值