最近工作中被一个非常简单的代码坑到了
//循环...
static int remainder = 0;
if (remainder++ % 8 == 0) {
// do something
} else if (remainder % 8 == 1) {
// do something
} else if (remainder % 8 == 2) {
// do something
} else if (remainder % 8 == 3) {
// do something
} else if (remainder % 8 == 4) {
// do something
} else if (remainder % 8 == 5) {
// do something
} else if (remainder % 8 == 6) {
// do something
} else if (remainder % 8 == 7) {
// do something
}
初看代码没什么问题,但一跑程序就崩溃了(do something只要不执行就会崩溃),简单的认为一个数n的余数只可能是0 ~ n - 1。事实上这种情况要建立在remainder值不变,上述代码
if (remainder++ % 8 == 0) 修改了变量值,而且最后也没有加else做异常处理;应该尽量避免以上问题。修改成如下:
//循环...
static int remainder = 0;
remainder++;
if (remainder % 8 == 0) {
// do something
} else if (remainder % 8 == 1) {
// do something
} else if (remainder % 8 == 2) {
// do something
} else if (remainder % 8 == 3) {
// do something
} else if (remainder % 8 == 4) {
// do something
} else if (remainder % 8 == 5) {
// do something
} else if (remainder % 8 == 6) {
// do something
} else if (remainder % 8 == 7) {
// do something
} else {
// do something
}