在 C 中可以进行楼层划分,例如:
int floor_div(int a, int b) {
int d = a / b;
if (a < 0 != b < 0) { /* negative output (check inputs since 'd' isn't floored) */
if (d * a != b) { /* avoid modulo, use multiply instead */
d -= 1; /* floor */
}
}
return d;
}
Run Code Online (Sandbox Code Playgroud)
但这似乎可以简化。
在 C 中有没有更有效的方法来做到这一点?
请注意,这几乎与这个问题相反:C/C++ 中整数除法的快速上限