【问题标题】:Double values doesn't match even through they are the same [duplicate]双精度值不匹配,即使它们相同 [重复]
【发布时间】:2022-12-11 04:10:50
【问题描述】:

我是 C++ 的新手 我有一个时间变量,在 while 循环中每次变化 0.01。 我正在尝试检测特定时间,但即使条件相同,C++ 也不会进入 if 条件。

void matchCashiers(){
                queue<int> cashierQueue = createCashierQueue(cashier);
                double time = 0;
                
                while(time<1){
                    if(time == arrival_times.front()){
                        cout << "cashier is full";
                        cashierQueue.pop();
                        arrival_times.pop();
                    }
                    
                    if(time == 0.71){ // when time equals to 0.71
                        cout << "cashier is free"; // there is no cashier is free print.
                        cashierQueue.push(1);
                        customer_times.pop();
                    }
                    cout << time <<endl; 
                    time = time + 0.01;
                
                }
            }

是因为我使用双数据类型吗?

【问题讨论】:

  • time 等于0.71 的可能性极小,即使您认为它应该等于。如果您尝试将 0.01 添加到自身 71 次,它尤其不会等于 0.71。请查看建议的副本以了解原因。
  • 是的,浮点运算是不准确的,不同的浮点数可以打印相同的。切勿将浮点数用于金钱。以美分(或便士或其他)计算你的钱并使用整数.
  • 不要为 C++ 问题标记 C。

标签: c++


【解决方案1】:

When the common IEEE-754 binary64 format is used for double in a good C implementation, the source text 0.01 is converted to the double value 0.01000000000000000020816681711721685132943093776702880859375, and the source text 0.71 is converted to 0.70999999999999996447286321199499070644378662109375.

当增量0.01000000000000000020816681711721685132943093776702880859375被重复添加到一个运行和中时,每次加法都存在舍入误差——加法的计算结果是实数算术和四舍五入到double中可表示的最接近的值。在将增量添加到初始化为零的运行总和后,结果为 0.710000000000000408562073062057606875896453857421875,这不等于 0.709999999999999996447286321199499070641378756

【讨论】:

  • 惊人的准确性。
【解决方案2】:

正如在您的帖子的 cmets 中已经提到的,“天真地”比较浮点数不是可行的方法。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-04-19
    • 1970-01-01
    相关资源
    最近更新 更多