[英]How do I properly implement "operator()" with "if constexpr" so that it works with std::generate?
[英]How do I properly implement `operator/`?
主要編輯:有人可以向我解釋如何修復操作員/使其正常工作嗎? 我意識到移位並非總是正確的,例如10 / 3
,這將導致無限循環。 那么我該如何解決呢?
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));
}
那這個呢:
int div; // Uninitialized variable.
如果流上的所有測試均失敗,會發生什么情況。
那么div可能有任何值。 如果它是0(或1),那么rhs將永遠不會達到0。
在表達式“ copyn>(copyed << 1)”中,“ copyed << 1”可能溢出,從而導致您正在觀察的無限循環。 我建議檢查溢出,或者使檢查更像“(copyn >> n)>復制”。
如果存在無限循環,您甚至將無法輸出-1。 -1不小於-123455,但您應該嘗試一下。 運算符<<沒什么錯,但是您對運算符/的假設有問題。 也有其他問題,但是我不確定是否應該做作業^ _ ^
我不確定這是否是問題,但它看起來像:
stream << out;
return stream;
在函數范圍之外,在類范圍內。
你可能想擺脫的一個}
年代以后else
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.