Mit Python 2.7 und -1/2 wird Ergebnis in -1 sein, da -1 Boden von -0.5 ist. Aber ich möchte das Ergebnis von 0 erhalten, was 1/2 (Ergebnis in 0) ist, dann negativ 1/2 (Endergebnis immer noch 0). Wundern Sie sich, wenn es eine elegante Möglichkeit gibt, dies zu tun?negative Zahl Teilung in Python
Meine aktuelle Lösung benutzt ABS und überprüft zuerst ihr Zeichen, das nicht sehr elegant scheint und sich fragt, ob jemand elegantere Lösungen hat?
Quellcode in Python 2.7,
a = -1
b = 2
print a/b # output -1
# prefer -(1/2) = 0
r = abs(a)/abs(b)
if (a > 0 and b < 0) or (a < 0 and b > 0):
r = -r
print r
Diese Antwort ist elegant, weil Sie nicht wirklich auf Fließkomma Arithmetik oder Zeichenfunktionen http://stackoverflow.com/questions/1986152/why-doesnt-python-have-a-sign-funktion – Elmex80s
@ Elmex80s, danke. Für "diese Antwort", welche Antwort meinst du? –