重要编辑:有人可以向我解释如何修复操作员/使其正常工作吗?我意识到移位并非总是正确的,例如10 / 3,这将导致无限循环。那么我该如何解决呢?整个代码位于http://ideone.com/GhF0euint128_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>(copyed > n)>复制”的检查。关于c++ - 如何正确实现`operator/`?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/6380897/
10-16 04:29