Java: Wie führe ich eine Ganzzahldivision durch, die eher auf -Infinity als auf 0 rundet?
(Hinweis: nicht das Selbe wiediese andere Frage da das OP niemals explizit eine Rundung in Richtung 0 oder -Infinity spezifiziert hat)
JLS 15.17.2 sagt, dass die Ganzzahldivision gegen Null rundet. Wenn ich willfloor()
-ähnliches Verhalten für positive Teiler (das Verhalten für negative Teiler ist mir egal), wie lässt sich dies am einfachsten erreichen, wenn alle Eingaben numerisch korrekt sind?
<code>int ifloor(int n, int d) { /* returns q such that n = d*q + r where 0 <= r < d * for all integer n, d where d > 0 * * d = 0 should have the same behavior as `n/d` * * nice-to-have behaviors for d < 0: * option (a). same as above: * returns q such that n = d*q + r where 0 <= r < -d * option (b). rounds towards +infinity: * returns q such that n = d*q + r where d < r <= 0 */ } long lfloor(long n, long d) { /* same behavior as ifloor, except for long integers */ } </code>
(Update: Ich möchte eine Lösung für beide habenint
undlong
Arithmetik.)