下面我附上代码,带有逻辑语句。通过查看这段代码,我可以看出它非常重复。
我的任务:给我一个 9x9 的网格,里面有 9 个盒子,我试图获取索引以开始从 (startRow/Col
) 到 (startRow/Col+ 2
).
vector<int> findBox(int row, int col){
int startRow;
int startCol;
if(row <= 2){
startRow = 0;
} else if(row > 2 && row <= 5){
startRow = 3;
} else if(row > 5 && row <= 8){
startRow = 6;
}
if(col <= 2){
startCol = 0;
} else if (col > 2 && col <= 5){
startCol = 3;
} else if(col > 5 && col <= 8){
startCol = 6;
}
vector<int> v;
v.push_back(startRow);
v.push_back(startCol);
return v;
}
我正在寻找可以更好地向我解释的人。还是我应该尝试重构代码并使用 switch?
谢谢。
jack
最佳答案
无需使用开关。利用将丢弃余数的整数除法:
int startRow{row / 3 * 3};
int startCol{col / 3 * 3};
函数变为:
vector<int> findBox(int row, int col){
int startRow{row / 3 * 3};
int startCol{col / 3 * 3};
vector<int> v;
v.push_back(startRow);
v.push_back(startCol);
return v;
}
关于c++ - 重构使用 if 语句的重复范围检查,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47144539/