2016-08-05 38 views
0
import math 

def roots4(outfile,a,b,c): 
    """Prints the solutions of 'x' for equation ax² + bx + c = 0 """ 
    d = b * b - 4 * a * c 
    if a == 0 and b == 0 and c == 0: 
     print "X = All complex/real numbers." 

    if c != 0: 
     print "X = No real solutions." 

    e = (-c/(b)) 
    if a == 0 and b > 0 < c: 
     print "There's only one solution: " + e 

    solutions = [str(-b/(2 * a))] 
    if a != 0 and d == 0: 
     print "There's only one solution: " + solutions 

    solutions2 = [str((-b + math.sqrt(d))/2.0/a), str((-b - math.sqrt(d))/2.0/a)] 
    if a != 0 and d > 0: 
     print "There's two solutions: " + solutions2 

    xre = str((-b)/(2 * a)) 
    xim = str((math.sqrt(-d))/(2 * a)) 
    solutions3 = [xre + " + " + xim +"i", xre + " - " + xim +"i"] 
    if a != 0 and d < 0: 
     print "Solutions are: " + solutions3 

Ich bekomme einen Fehler "ZeroDivisionError: float division by zero", weil ich durch Null dividiere, wenn "b" "0" aus einer Eingabedatei ist. Wie kann ich den Fehler umgehen, damit er den gewünschten Text drucken kann? Meine gewünschte Ausgabe muss die gewünschte Druckanweisung sein, wenn die "if" Bedingungen erfüllt werden.Wenn didving von 0, möchte ich es gegebenen Text drucken

wo (a, b, c)

0.0, 0.0, 0.0 

    0.0, 0.0, 1.0 

    0.0, 2.0, 4.0 

    1.0, 2.0, 1.0 

    1.0, -5.0, 6.0 

    1.0, 2.0, 3.0 
+0

Nur ... nicht teilen durch Null? Warum hast du überhaupt eine Division mit einem Nenner, der hier null sein könnte? – user2357112

+0

Du bist nicht einmal * mit * 'e'! – user2357112

+0

Ich löse für x in der Gleichung "ax² + bx + c = 0". Wenn also a, b, c gleich 0 sind, kann x "Alle komplexen Zahlen" sein. Es sei denn, Sie können sich einen anderen Weg vorstellen, um den Fehler zu umgehen, ich bin dafür offen. –

Antwort

0

Ich weiß nicht, den Python. Aber kenne das Konzept.

Bitte korrigieren Sie den Python-Code-Fehler.

Druckt die Lösungen von ax² + bx + c = 0

def roots4(outfile,a,b,c): 
d = (b * b) - (4 * a * c)  


if a == 0 and b == 0 and c==0: 
    print "This is not quadratic equations" 
if a == 0 and b == 0: 
    print "Invalid equations" 
if a == 0: 
    e = [str(-b/(2 * a))] 
    print "There's only one solution: X=" + e   
if d == 0 : 
    solutions = -b/(2 * a) 
    print "Two roots are same X = " + solutions 
if d > 0: 
    solutions2 = [str((-b + math.sqrt(d))/(2.0 * a)), str((-b - math.sqrt(d))/(2.0 * a))] 
    print "There's two solutions: " + solutions2 
if d < 0: 
    xre = str((-b)/(2 * a)) 
    xim = str((math.sqrt(-d))/(2 * a)) 
    solutions3 = [xre + " + " + xim +"i", xre + " - " + xim +"i"] 
    print "Solutions are: " + solutions3 
+0

Ja, ich denke du kannst es so sehen. Es muss mit den gegebenen (a, b, c) funktionieren, die ich oben angegeben habe. (0.0, 0.0, 0.0) (0.0, 0.0, 1.0) (0.0, 2.0, 4.0) (1.0, 2.0, 1.0) (1.0, -5.0, 6.0) (1.0, 2.0 , 3.0) –

+0

@JesusAnaya Lass mich wissen, meine Logik ist richtig. –

+0

Ja, es ist korrekt –