如何正确实现“operator/”
How do I properly implement `operator/`?
主要编辑:
有人能向我解释如何修复运算符/使其正常工作吗?我意识到偏移并不总是正确的,例如对于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
之后的一个}
。
相关文章:
- 为不同配置设置MSVC_RUNTIME_LIBRARY的正确方法是什么
- CMake-按正确顺序将项目与C运行时对象文件链接
- C++我的数学有什么问题,为什么我的代码不能正确循环
- 用于访问容器<T>数据成员的正确 API
- 如何使用Luacneneneba API正确读取字符串和表参数
- 如何使用用户输入在C++中正确填充2D数组
- node-gyp 在 macOS 上未正确链接库
- C++从另一个类访问公共静态向量的正确方法是什么
- 如何在 C 中正确使用 libiconv 使其不会报告"Arg list too long"?
- 为什么我的for循环不能正确获取argv
- 如何取消对nullptr的屏蔽,返回正确的对象
- AES加密到解密未正确输出
- 使用C++程序合并排序没有得到正确的输出
- 在 c++ 中拥有一组结构的正确方法是什么?
- 函数何时会在c++中包含stack_Unwind_Resume调用
- 使用2个键的cpp-stl::优先级队列排序不正确
- 当试图交换可变模板类时,如何正确地重载operator=
- 带有"operator="和向量的c ++类,我不知道如何正确使用它
- 我可以在 c++ 中正确设置 std::vector by operator[] 的第 n 个值吗?
- 如何正确实现“operator/”