比较两个double值不能正常工作

比较两个double值不能正常工作

本文介绍了c ++比较两个double值不能正常工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

查看此代码:

#include <cmath>
#include <iostream>
using namespace std;
class Sphere
{
    double r;
public:
    double V() const { return (4/3) * 3.14 * pow(r,3); }
    bool equal(const Sphere& s) const
    {
        cout  << V() << " == " << s.V() << " : " << ( V() == s.V() );
        return ( V() == s.V() );

    }

    explicit Sphere(double rr = 1): r(rr){}

};
main()
{
    Sphere s(3);
    s.equal(s);
}

输出 84.78 == 84.78:0 这意味着相同的方法不会每次返回相同的值,即使所有参数都是静态的吗?

The output is 84.78 == 84.78 : 0 which means the same method doesn't return the same value every time, even though all parameters are static?

但如果我写<$ c方法定义中的<$ c> 3.0 而不是 3.14

double V() const { return (4/3) * 3.0 * pow(r,3); }

然后,输出是: 84.78 == 84.78:1

Then, the output is: 84.78 == 84.78 : 1

这是怎么回事?我需要这个方法,对于我的程序,这将比较两个对象的卷,但它是不可能的?我撞了我的头这么久,找出是什么原因的问题,幸运的是我发现它,但现在我不明白为什么?它是否与编译器(GCC)有关,或者我在这里缺少重要的东西?

What is going on here? I need this method, for my program, which will compare volumes of two objects, but it is impossible? I banged my head for so long to figure out what is the cause of the problem and luckily I found it, but now I don't understand why?? Does it have something to do with the compiler (GCC) or am I missing something important here?

推荐答案

== 运算符非常容易出错; 应该相等的两个值可能不是由于算术舍入误差。比较这些的常见方法是使用epsilon:

Comparing floating point values using the == operator is very error prone; two values that should be equal may not be due to arithmetic rounding errors. The common way to compare these is to use an epsilon:

bool double_equals(double a, double b, double epsilon = 0.001)
{
    return std::abs(a - b) < epsilon;
}

这篇关于c ++比较两个double值不能正常工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-24 10:03