双精度C ++ [英] double precision C++
问题描述
template< class T>
和
bool eq(T one,T two)
{
if(one == two)
return true;
else
返回false;
$ b $ p $它可以和eq(0.8,0.8)一起使用,但是不起作用与eq(0.8 * 0.2,0.16)。正如我所提到的,我认为它必须做双精度,因为它也适用于int eq(8 * 2,16)。解决方案首先,您应该阅读以下文章中的一篇(或两篇):每台计算机科学家应该知道浮点运算和浮点运算的危险。 p>
如果您正在寻找您的模板的解决方案,我会建议使用 T == double
T == float $ c $的情况,rel =noreferrer> template specialization c>。
I think the precision of double is causing that problem, as it was described in similiar posts, but I would like to know if there is a way to achieve correct result. I'm using function template which compares two parameters and returns true if they are equal.
template <class T> bool eq(T one, T two) { if (one == two) return true; else return false; }
It works with eq (0.8,0.8), but it doesn't work with eq (0.8*0.2,0.16). As I mentioned I assume it has to do with double precision as it also works fine with int eq(8*2,16).
解决方案First you should read one (or both) of these articles: What Every Computer Scientist Should Know About Floating-Point Arithmetic and The Perils of Floating Point.
If you are looking for a solution for your template, I would suggest using template specialization for the cases where
T==double
andT==float
.这篇关于双精度C ++的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!