这次xhd面临的问题是这样的:在一个平面内有两个点,求两个点分别和原点的连线的夹角的大小。
注:夹角的范围[0,180],两个点不会在圆心出现。
Input
输入数据的第一行是一个数据T,表示有T组数据。
每组数据有四个实数x1,y1,x2,y2分别表示两个点的坐标,这些实数的范围是[-10000,10000]。
Output
对于每组输入数据,输出夹角的大小精确到小数点后两位。
Sample Input
2 1 1 2 2 1 1 1 0
Sample Output
0.00 45.00
果然我还是太弱了,一道水题都写的那么麻烦,写的那么久。。。
思路:
1、分别看两个点位于哪个象限,求出与坐标轴的夹角,进行加减。
2、用向量法求,a*b=|a||b|cos(α)=x1x2+y1y2;
用atan()函数时要注意返回值为弧度,要转换成角度,角度=弧度*180/PI。
关于atan()和atan2()讲解的博客:
https://www.cnblogs.com/dutlei/archive/2013/01/14/2860332.html
https://blog.csdn.net/tuyang120428941/article/details/5822041
ac代码:
#include<iostream>
#include<stdio.h>
#include<algorithm>
#include<math.h>
#include<cstring>
#include<string.h>
#include<queue>
#define PI acos(-1.0)
using namespace std;
typedef long long ll;
int main()
{
int t;
scanf("%d",&t);
while(t--)
{
double x1,x2,y1,y2;
scanf("%lf%lf%lf%lf",&x1,&y1,&x2,&y2);
if(y1/x1>0)
{
if(y2/x2>0)
{
double a1=atan(y1/x1)*180/PI;
double a2=atan(y2/x2)*180/PI;
double ans=a1>a2?a1-a2:a2-a1;
printf("%.2lf\n",ans>=0?ans:-ans);
}
else if(y2/x2<0)
{
double a1=atan(y1/x1)*180/PI;
double a2=atan(y2/x2)*180/PI;
double ans=180-a1+a2;
printf("%.2lf\n",ans>=0?ans:-ans);
}
else if(x2>0)
{
double a1=atan(y1/x1)*180/PI;
printf("%.2lf\n",a1);
}
else
{
double a1=atan(y1/x1)*180/PI;
printf("%.2lf\n",180-a1);
}
}
else if(y1/x1<0)
{
if(y2/x2>0)
{
double a1=atan(y1/x1)*180/PI;
double a2=atan(y2/x2)*180/PI;
double ans=180+a1-a2;
printf("%.2lf\n",ans);
}
else if(y2/x2<0)
{
double a1=atan(y1/x1)*180/PI;
double a2=atan(y2/x2)*180/PI;
double ans=-a1+a2;
printf("%.2lf\n",ans>=0?ans:-ans);
}
else if(x2>0)
{
double a1=atan(y1/x1)*180/PI;
printf("%.2lf\n",180+a1);
}
else
{
double a1=atan(y1/x1)*180/PI;
printf("%.2lf\n",-a1);
}
}
else if(x1>0)
{
if(y2/x2>0)
{
double a2=atan(y2/x2)*180/PI;
printf("%.2lf\n",a2);
}
else if(y2/x2<0)
{
double a2=atan(y2/x2)*180/PI;
double ans=180+a2;
printf("%.2lf\n",ans>=0?ans:-ans);
}
else if(x2>0)
{
double a1=0;
printf("%.2lf\n",a1);
}
else
{
double a1=180;
printf("%.2lf\n",a1);
}
}
else{
if(y2/x2>0)
{
double a2=atan(y2/x2)*180/PI;
printf("%.2lf\n",180-a2);
}
else if(y2/x2<0)
{
double a2=atan(y2/x2)*180/PI;
double ans=-a2;
printf("%.2lf\n",ans>=0?ans:-ans);
}
else if(x2>0)
{
double a1=180;
printf("%.2lf\n",a1);
}
else
{
double a1=0;
printf("%.2lf\n",a1);
}
}
}
return 0;
}
向量法代码:
#include<iostream>
#include<stdio.h>
#include<algorithm>
#include<math.h>
#include<cstring>
#include<string.h>
#include<queue>
#define PI acos(-1.0)
using namespace std;
int main()
{
double x1,x2,y1,y2;
double a1,a2;
int t;
scanf("%d",&t);
while (t--)
{
scanf("%lf%lf%lf%lf",&x1,&y1,&x2,&y2);
a1=sqrt(x1*x1+y1*y1)*sqrt(x2*x2+y2*y2);
a2=x1*x2+y1*y2;
printf("%.2lf\n",acos(a2/a1)*180.0/PI);
}
return 0;
}