如何在 c++ 中处理 -nan 输出

How to handle -nan output in c++

本文关键字:处理 -nan 输出 c++      更新时间:2023-10-16

假设我有一个函数来计算一对点之间的欧氏距离。pointpoint_pair是定义为以下两个结构:

struct point {
int x, y;
}

struct point_pair {
point a, b;
}

以下函数以一对点作为输入来计算距离:

double calc_distance(point_pair pair)
{
return (sqrt((pair.a.x - pair.b.x) * (pair.a.x - pair.b.x) + (pair.a.y - pair.b.y) * (pair.a.y - pair.b.y)));
}

该函数适用于小点对值;但对于点对,例如:

651760491 595516649
716636914 955747792

输出为-nan

我不确定如何解决这个问题,我应该使用其他东西来代替双倍吗?

以下是整个代码: https://pastebin.com/5XEr9bTD

正确的方法是使用标准的hypot()函数。

https://en.cppreference.com/w/cpp/numeric/math/hypot

"计算 x 和 y 的平方和的平方根,在计算的中间阶段不会过度溢出或下溢。">

最好不要将int用于点坐标:

#include <iostream>
#include <cmath>
struct point { double x, y; };
struct point_pair { point a, b; };
double calc_distance(point_pair pair) {
return (std::sqrt((pair.a.x - pair.b.x) * (pair.a.x - pair.b.x) + (pair.a.y - pair.b.y) * (pair.a.y - pair.b.y)));
}
int main() {
point_pair pp{{651760491, 595516649}
, {716636914, 955747792}};
std::cout << calc_distance(pp) << 'n';
}

但是,如果您有理由这样做,那么至少将坐标差异转换为double

struct point { int x, y; };
struct point_pair { point a, b; };
double calc_distance(point_pair pair) {
return (std::sqrt(double(pair.a.x - pair.b.x) * (pair.a.x - pair.b.x) + double(pair.a.y - pair.b.y) * (pair.a.y - pair.b.y)));
}

因为否则您在大订单中会遇到整数溢出,而签名溢出是C++中的UB。