课后自主练习(排序)1027. 极坐标排序 easy《编程思维与实践》个人学习笔记

题目

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
输入
3
5
1.0 1.0
2.0 2.0
-1.0 1.0
0 1.0
1.0 0
1
0 -1.0
6
1.0 1.0
0 1.0
1.0 0
-1.0 1.0
-1.0 -1.0
1.0 -1.0

思路

经典的 创造类,输入(并转化对应的量),排序,输出
需要注意的是由于atan只能转成一个pi的范围,所以要根据极坐标在哪个象限来分类讨论进行+npi/2的处理

代码

#include<iostream>
#include<cmath>
#define db double
using namespace std;

struct polar
{
    db x;
    db y;
    db angle;
    db chord;

    db hypoteuse(db x, db y)
    {
        db temp = pow(x,2) + pow(y,2);
        temp = sqrt(temp);
        return temp;
    }

    db Pangle(db x ,db y)
    {
        if(x == 0 && y > 0)
        {return acos(0);}
        else if(x == 0 && y < 0)
        {return 3 * acos(0);}

        db k = (db)y / (db)x;
        
        if(x > 0 && y >= 0)
        {return atan(k);}
        else if(x > 0 && y < 0)
        {return 4 *acos(0) + atan(k);}
        else if(x < 0 && y > 0)
        {return 2 * acos(0) + atan(k);}
        else
        {return  2 * acos(0) + atan(k);}

    }

    void init()
    {
        chord = hypoteuse(x,y);
        angle = Pangle(x,y);
    }
};

int cmp(const void *q1, const void *q2)
{
    polar * p1 = (polar *)q1;
    polar * p2 = (polar *)q2;

    if(p1->angle == p2->angle)
    {
        if(p1->chord > p2->chord)
        {return -1;}
        else
        {return 1;}
    }
    if(p1->angle > p2->angle)
    {return 1;}
    else
    return -1;
}

void print(polar *a,int len)
{
    for(int i = 0; i < len; i++)
        printf("(%.4lf,%.4lf)",a[i].chord,a[i].angle);
}



int main()
{
    int total;
    cin >> total;
    
    for(int i = 0; i < total; i++)
    {
        int allp;
        cin >> allp;
        polar * point = new polar[allp];

        for(int j = 0; j < allp; j++)
        {
            cin >> point[j].x >> point[j].y;
            point[j].init();
        }
        cout << "case #"<<i<<":" << endl;
        // for(int i = 0; i < allp; i++)
        // {
        //     printf("(%.4lf,%.4lf)\n",point[i].chord,point[i].angle);
        // }
        
        
        qsort(point,allp,sizeof(polar),cmp);
        for(int i = 0; i < allp; i++)
        {
            printf("(%.4lf,%.4lf)\n",point[i].chord,point[i].angle);
        }
        delete point;
    }
    
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值