C++ c++;将浮点数四舍五入以设置精度

C++ c++;将浮点数四舍五入以设置精度,c++,floating-point,precision,C++,Floating Point,Precision,我希望对浮点数进行四舍五入以设置精度并从函数返回结果。例如,我目前有以下功能: inline bool R3Point:: operator==(const R3Point& point) const { // Return whether point is equal return ((v[0] == point.v[0]) && (v[1] == point.v[1]) && (v[2] == point.v[2])); } 我希望做的不是直

我希望对浮点数进行四舍五入以设置精度并从函数返回结果。例如,我目前有以下功能:

inline bool R3Point::
operator==(const R3Point& point) const
{
  // Return whether point is equal
  return ((v[0] == point.v[0]) && (v[1] == point.v[1]) && (v[2] == point.v[2]));
}
我希望做的不是直接比较
v[I]==point.v[I]
,而是只比较数字到某一设定精度,这样如果
v[I]=0.33349999999996
point.v[I]=0.33350000000000002
,我的相等比较结果将为真

<>我知道有一个C++ <代码> SMANIP StActudio(int n);<代码>函数,我看到它在使用
cout
在屏幕上显示输出时使用了很多。但是,我不确定这是否可以在我描述的函数中使用


谢谢。

比较两个浮点数(比如a和b)最好使用以下方法:abs(a-b)通常,
=
不应用于比较双精度,您应该执行以下操作:

if(v[0] - point.v[0] < 1e-9) { }
if(v[0]-point.v[0]<1e-9){

如果您不确定符号,可以使用
abs
fabs
,并相应地更改精度1e-9。

相应地更改精度1e-9是什么意思?在我的例子中,我不确定符号,所以我会使用一些if(fabs(v[0]-point.v[0])<1e-9。我的意思是,您需要根据需要精确的位数来更改1e-9。请确保编写std::abs而不仅仅是abs,否则您可能会意外地得到只处理整数的C函数。祝你快乐。。。