C/C++ math.h中的函数传相同参数进去返回的值一定相同吗?

我写的是C++

我希望对一些向量按其方向排序。我用下面的struct存向量

struct V { double x, y };

写下面的比较函数

inline bool operator<(const V &a, const V &b)
{
    return atan2(a.y,a.x)<atan2(b.y,b.x);
}

我把它传进std::sort里,然后排序过程中越界了。具体数据较大,不便分析。

然后我把V改成下面这样,并写一个构造函数

struct V
{
    double x, y, t;
    V(double _x, double _y) : x(_x), y(_y), t(atan2(y,x)) {}
};

比较函数改成

inline bool operator<(const V &a, const V &b)
{
    return a.t<b.t;
}

这样就没问题了。

我原来认为atan2就算计算有误差,传相同的参数进去也应该返回相同的值。上面的情况意味着不是这样吗?还是有别的什么问题?

以下为更新内容

我又做了如下实验,更没有头绪

代码:

#include<cmath>
#include<iostream>
using namespace std;

int main()
{
    int x=-3, y=7;
    double tmp=atan2(y,x);
    cout << (tmp==atan2(y,x)) << endl;
    double tmp2=atan2(y,x);
    cout << (tmp==tmp2) << endl;
    return 0;
}

输出:

0
1

阅读 4.5k
2 个回答
新手上路,请多包涵

在构造struct的时候 x,y成员变量初始化一下吧..

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题