如何在 c++ 中处理 -nan 输出
How to handle -nan output in c++
假设我有一个函数来计算一对点之间的欧氏距离。point
和point_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。
相关文章:
- 警告处理为错误这里有什么问题
- 在C#中处理C++指针而不使用unsafe的最佳方法
- 处理多个异常集合的C++方法
- 找不到成员对象:没有名为get_event()的成员,也处理多态性和向量
- 使用流处理接收到的数据
- 获取日期异步信号安全吗?如果在信号处理程序中使用,它会导致死锁吗
- 处理小于cpu数据总线的数据类型.(c++转换为机器代码)
- 基于多个条件处理地图中的所有元素
- 如何用数字处理log(0)
- SSL上的`curl_easy_send`和`curl_asy_recv`:如何处理`CURLE_AGAIN`
- 错误处理.将系统错误代码映射到泛型
- 从文本文件中读取时钟时间和事件时间并进行处理
- 在运行时处理类型擦除的数据-如何不重新发明轮子
- 在for循环中使用auto vs decltype(vec.size())来处理字符串的向量
- 用于矢量处理的多个线程
- 如何在 c++ 中处理 -nan 输出
- 在 C++ 节点 nan 插件中处理 JavaScript 对象
- 仅处理整数和浮点时获取NAN
- 浮点NaN取决于C++中不相关的异常处理
- NaN在不同g++版本中的处理方式不同