为什么当我从两个角度的和本身显示为 180 时减去 180 时得到错误答案?
Why I get an incorrect answer when I substract 180 from the sum of the two angles when the sum itself shows as 180?
程序得到 4 个点(它们的坐标)形成一个凸形,应该给我角度 A2+角度 A4 - 180 度。例如:
1 3
0 2
1 1
2 2
我得到 uA2=90 和 uA4=90,但是当我执行 uA2+uA4-180 时,我得到 2.0568e-007,而不是 0。但是当我只执行 uA2+uA4 时,我得到 180。对不起如果有人问了类似的问题,但我不知道如何搜索它。谁能告诉我为什么会发生这种情况以及如何修复它以显示正确答案?代码:
#include <iostream>
#include <fstream>
#include <cmath>
#define PI 3.14159265
using namespace std;
ifstream f("date.in");
struct punct
{
double x,y;
}A1,A2,A3,A4;
int main()
{
double uA2,uA4;
f>>A1.x>>A1.y>>A2.x>>A2.y>>A3.x>>A3.y>>A4.x>>A4.y;
//calculate cos of both angles
uA2=((A1.x-A2.x)*(A3.x-A2.x)+(A1.y-A2.y)*(A3.y-A2.y))/
(sqrt((A1.x-A2.x)*(A1.x-A2.x)+(A1.y-A2.y)*(A1.y-A2.y))*sqrt((A3.x-A2.x)*(A3.x-A2.x)+(A3.y-A2.y)*(A3.y-A2.y)));
uA4=((A1.x-A4.x)*(A3.x-A4.x)+(A1.y-A4.y)*(A3.y-A4.y))/
(sqrt((A1.x-A4.x)*(A1.x-A4.x)+(A1.y-A4.y)*(A1.y-A4.y))*sqrt((A3.x-A4.x)*(A3.x-A4.x)+(A3.y-A4.y)*(A3.y-A4.y)));
//calculate angles
uA2=acos(uA2)*180.0/PI;
uA4=acos(uA4)*180.0/PI;
//the part that gives me an incorrect answer
cout<<uA2+uA4-180<<endl;
}
对于浮点计算,我们可以使用一些非常小的边际误差偏移值,例如1e-6。
double diff = uA2 + uA4 - 180, threshold = 1e-6;
if (diff < threshold && diff > -threshold) cout << "0" << endl;
else cout << diff << endl;
// cout<<uA2+uA4-180<<endl;
程序得到 4 个点(它们的坐标)形成一个凸形,应该给我角度 A2+角度 A4 - 180 度。例如:
1 3
0 2
1 1
2 2
我得到 uA2=90 和 uA4=90,但是当我执行 uA2+uA4-180 时,我得到 2.0568e-007,而不是 0。但是当我只执行 uA2+uA4 时,我得到 180。对不起如果有人问了类似的问题,但我不知道如何搜索它。谁能告诉我为什么会发生这种情况以及如何修复它以显示正确答案?代码:
#include <iostream>
#include <fstream>
#include <cmath>
#define PI 3.14159265
using namespace std;
ifstream f("date.in");
struct punct
{
double x,y;
}A1,A2,A3,A4;
int main()
{
double uA2,uA4;
f>>A1.x>>A1.y>>A2.x>>A2.y>>A3.x>>A3.y>>A4.x>>A4.y;
//calculate cos of both angles
uA2=((A1.x-A2.x)*(A3.x-A2.x)+(A1.y-A2.y)*(A3.y-A2.y))/
(sqrt((A1.x-A2.x)*(A1.x-A2.x)+(A1.y-A2.y)*(A1.y-A2.y))*sqrt((A3.x-A2.x)*(A3.x-A2.x)+(A3.y-A2.y)*(A3.y-A2.y)));
uA4=((A1.x-A4.x)*(A3.x-A4.x)+(A1.y-A4.y)*(A3.y-A4.y))/
(sqrt((A1.x-A4.x)*(A1.x-A4.x)+(A1.y-A4.y)*(A1.y-A4.y))*sqrt((A3.x-A4.x)*(A3.x-A4.x)+(A3.y-A4.y)*(A3.y-A4.y)));
//calculate angles
uA2=acos(uA2)*180.0/PI;
uA4=acos(uA4)*180.0/PI;
//the part that gives me an incorrect answer
cout<<uA2+uA4-180<<endl;
}
对于浮点计算,我们可以使用一些非常小的边际误差偏移值,例如1e-6。
double diff = uA2 + uA4 - 180, threshold = 1e-6;
if (diff < threshold && diff > -threshold) cout << "0" << endl;
else cout << diff << endl;
// cout<<uA2+uA4-180<<endl;