编写一个c++程序,计算四个点所构成的两条直线的夹角
setprecision(n)描述:可以控制输出流显示浮点数的数字个数。C++默认的输出流数值有效位是6。
平面上给定4个点的坐标A B C D,分别表示直线AB和CD。坐标均为绝对值不超过100的整数。计算出这两条直线所成的锐角是多少度。(保留两位小数)
注意:当两直线平行或者重合,答案为0。
测试举例:
测试输入:0 0 1 0 0 0 0 1
预期输出:90.00
测试输入:16 34 21 87 98 23 12 9
预期输出:75.36
方法1:
#include<iostream>
#include<cmath>
#include<iomanip>
#define pi 3.1415926;
using namespace std;
int main()
{
double x1,y1,x2,y2,x3,y3,x4,y4;
long double x,y;
cin>>x1>>y1>>x2>>y2>>x3>>y3>>x4>>y4;
x=(x1-x2)*(x1-x2)+(y1-y2)*(y1-y2);
y=(x3-x4)*(x3-x4)+(y3-y4)*(y3-y4);
long double s1,s2;
s1=sqrt(x);
s2=sqrt(y);
long double s3;
s3=(x2-x1)*(x4-x3)+(y2-y1)*(y4-y3);
long double s4;
s4=abs(s3);
long double ans,ans2;
ans2=s4/(s1*s2);
ans=acos(ans2);
long double ans3;
ans3=(180*ans)/pi;
cout<<fixed<<setprecision(2)<<(long double)ans3;
return 0;
}
方法2
#include<iostream>
#include<cmath>
#include<iomanip>
using namespace std;
const double PI = 3.14159265358979323846;
struct Point {
double x, y;
};
double angleBetween(const Point& O, const Point& A) {
if (A.x == O.x)
{
if (A.y <= O.y)
{
return -PI / 2.0;
}
else
{
return PI / 2.0;
}
}
double cross = (A.y - O.y) / (A.x - O.x);
if (A.x <= O.x)
{
return PI + atan(cross);
}
return atan(cross);
}
int main()
{
double x1, y1, x2, y2, x3, y3, x4, y4;
cin >> x1 >> y1 >> x2 >> y2 >> x3 >> y3 >> x4 >> y4;
Point A = { x1,y1 };
Point B = { x2,y2 };
Point C = { x3, y3 };
Point D = { x4, y4 };
double ans1 = angleBetween(A, B);
double ans2 = angleBetween(C, D);
double ans3 = abs(ans2 - ans1);
double ans4 = (180 * ans3) / PI;
if (ans4 > 90) {
ans4 = 180 - ans4;
}
cout << fixed << setprecision(2) << (double)ans4;
return 0;
}