除法(mod)的结果表现得很奇怪

时间:2013-06-18 15:05:00

标签: c++

这应该是一个非常基本的东西,但不知怎的,我没有看到问题。

#include <iostream>

template <int dim>
inline
void
i2c(const int & ind, int & i, int &j) {
        i = (int) ind / dim;
        j =       ind & dim;
        //j = ind - i*dim;
}

static const int dim = 2;

int main() {
    int i,j;

    for (unsigned int c = 0; c < dim*dim; c++) {
        i2c<dim>(c,i,j);
        std::cout<<c<<"/"<<dim<<"="<<i<<"; "<<c<<"&"<<dim<<"="<<j<<std::endl;
    } 
    return 0;
}

这是code

输出结果为:

0/2=0; 0&2=0
1/2=0; 1&2=0
2/2=1; 2&2=2
3/2=1; 3&2=2

如果我使用j = ind - i*dim - 一切正常。

EDIT1 : 有人可以删除这个问题,这样我就不会因为失明而感到羞耻吗? ;)

1 个答案:

答案 0 :(得分:2)

你可能意味着j = ind & (dim - 1);,假设dim是2的幂。

提取低阶位,具有计算模数的效果。当然,大多数编译器都会看到这个优化来自一英里之外,所以你真的应该使用%运算符来实现模数:

j = ind % mod;