2017-12-02 90 views
0

该程序获得4点(他们的坐标),形成一个凸形的图形,应该给我角度A2 +角度A4 - 180度。对于例如:当总和本身显示为180时,为什么我从两个角度的总和中减去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; 
} 
+4

的[是浮点运算坏了吗?](https://stackoverflow.com/questions/588004/is-floating-point-math-broken) –

+0

我通过计算也有这个问题,可能的复制'罪(2 * PI)'这也返回这个值而不是0.所以我认为这些功能不是很精确? –

+0

浮点数学是一个近似值。这是简单的原因 - 更多地阅读它,转到指定的链接或对该主题进行谷歌搜索。 – PaulMcKenzie

回答

1

对于浮点计算,我们可以使用一些非常小的偏移值作为边缘错误,例如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; 
相关问题