比较双精度堆栈导致Always Equal

Comparing Stacks of Doubles resulting in Always Equal

本文关键字:Always Equal 双精度 堆栈 比较      更新时间:2023-10-16

我试着比较两个堆栈,看看它们是否相等。不幸的是,这段代码使得我所有的比较都表明堆栈是相等的,即使堆栈不是相等的。

Stack_implementation.cpp snippet:

int DoubleStack::operator==(DoubleStack& rhs)
{
    int equal = 1;
    for (int i = 0; i <= tos; i++)         //tos is the top of the stack indicator
    {                                      //it tells how big the stack is
        if (data[i] != rhs.data[i])
        {
            equal = 0;
            break;
        }
    }
    return equal;
}

main.cpp相关片段:

{
    cout << "Comparing stacks..." << endl;
    if (stack1 == stack2)
        cout << "stack1 = stack2." << endl;
    else
        cout << "stack1 != stack2." << endl;
}

输出总是stack1 = stack2

有人知道怎么回事吗?

第一个检查应该是堆栈的大小;如果大小不相同,堆栈就不能相等。所编写的代码可能超出其中一个堆栈的末端。

你也可以尽快返回,只要你发现一个不同的项目。没有必要继续循环。

bool DoubleStack::operator==(DoubleStack& rhs)
{
    if (tos != rhs.tos) {
        return false;
    }
    for (int i = 0; i <= tos; i++)         //tos is the top of the stack indicator
    {                                      //it tells how big the stack is
        if (data[i] != rhs.data[i])
        {
           return false;
        }
    }
    return true;
}