如何正确实现“operator/”

How do I properly implement `operator/`?

本文关键字:operator 何正确 实现      更新时间:2023-10-16

主要编辑: 有人能向我解释如何修复运算符/使其正常工作吗?我意识到偏移并不总是正确的,例如对于10 / 3,这将导致无限循环。那么我该怎么解决呢?

整个代码位于http://ideone.com/GhF0e

uint128_t operator/(uint128_t rhs){
    // Save some calculations ///////////////////////
    if (rhs == 0){
        std::cout << "Error: division or modulus by zero" << std::endl;
        exit(1);
    }
    if (rhs == 1)
        return *this;
    if (*this == rhs)
        return uint128_t(1);
    if ((*this == 0) | (*this < rhs))
        return uint128_t(0, 0);
    // //////////////////////////////////////////////
    uint128_t copyn(*this), quotient = 0;
    while (copyn >= rhs){
        uint128_t copyd(rhs), temp(1);
        // shift the divosr to match the highest bit
        while (copyn > (copyd << 1)){
            copyd <<= 1;
            temp <<= 1;
        }
        copyn -= copyd;
        quotient += temp;
    }
    return quotient;
}

这是正确的吗?

    uint128_t operator/(uint128_t rhs){
        // Save some calculations ///////////////////////
        if (rhs == 0){
            std::cout << "Error: division or modulus by zero" << std::endl;
            exit(1);
        }
        if (rhs == 1)
            return *this;
        if (*this == rhs)
            return uint128_t(1);
        if ((*this == 0) | (*this < rhs))
            return uint128_t(0);
        uint128_t copyd(rhs);
        // Checks for divisors that are powers of two
        uint8_t s = 0;
        while ((copyd.LOWER & 1) == 0){
            copyd >>= 1;
            s++;
        }
        if (copyd == 1)
            return *this >> s;
        // //////////////////////////////////////////////
        uint128_t copyn(*this), quotient = 0;
        copyd = rhs;
        uint8_t n_b = 255, d_b = 0;
        while (copyd){
            copyd >>= 1;
            d_b++;// bit size of denomiator
        }
        copyd = rhs;
        while (n_b > d_b){
            // get the highest bit of dividend at current step
            n_b = 0;
            uint128_t copycopyn(copyn);
            while (copycopyn){
                copycopyn >>= 1;
                n_b++;
            }
            uint8_t highest_bit = n_b - d_b - 1;
            copyn -= copyd << highest_bit;
            quotient += uint128_t(1) << highest_bit;
        }
        if (n_b == d_b)
            quotient++;
        return quotient;
    }

这似乎是正确的,除了我在10的时候得到了随机的大值,尽管我的mod函数只是

    uint128_t operator%(uint128_t rhs){
        return *this - (rhs * (*this / rhs));
    }

在表达式"copyn>(copyd<<1)"中,"copyd&llt;<1"可能溢出,导致您观察到的无限循环。我建议检查溢出,或者使检查更像"(copyn>>n)>coped"。

这个怎么样:

int div;  // Uninitialized variable.

如果流上的所有测试都失败了,会发生什么
那么div可以有任何值。如果是0(或1),则rhs将永远不会达到0。

如果有一个无限循环,您甚至无法输出-1-1没有-123455那么小,但你应该试试。运算符<lt;但是你对operator/的假设有问题。还有其他问题,但我不确定我是否应该做你的家庭作业^_^

我不确定这是否是问题所在,但看起来像是:

stream << out;
return stream;

在函数之外,在类范围内。

您可能想去掉else之后的一个}