2017-10-30 4 views
0

Das Ergebnis dieser Funktion ist zweimal aus irgendeinem Grund auszudrucken. Gibt es einen Grund warum? Ich kann das nicht lösen. Ich habe es eine Stunde lang angeschaut und versucht herauszufinden, warum es so ist.For-Schleife in Python zweimal drucken

import math 


def pop1(t): 
    r1 = 1/(1 + (math.e ** -(t))) 
    print(r1) 

def pop2(t): 
    r1 = 1/(1 + (math.e ** -(t))) 
    return r1 




def main(): 
    for t in range(-6, 7): 
     print(t, end=" ") 
     pop1(t) 

    total = 0 
    for t in range(-6, 7): 
     result = pop2(t) 
     total = total + result 
     print(t, result) 

    print('Total is', total) 



main() 
+0

Bitte beheben Vertiefung. Es scheint nur so zu sein. Denn nach dem Ausführen Ihres Codes wurde nur einmal gedruckt. – scharette

+0

mark 'print (r1)' und 'print (t, end =" ")' – Wen

Antwort

0

Sein nicht zweimal gedruckt wird, es zu tun, was Sie machen es zu tun:

Ihr zweimaliges Drucken verursacht:

print(r1) 

und

print(t, end=" ") 

Zweitens Ihre Vertiefung des Codes ist nicht richtig, Ihre Gesamt nicht Ergebnis ist das Hinzufügen, wenn Sie total=total+result außerhalb der Schleife tun, hier sind alle fix Ihres Codes:

import math 

def pop1(t): 
    r1 = 1/(1 + (math.e ** -(t))) 


def pop2(t): 
    r1 = 1/(1 + (math.e ** -(t))) 
    return r1 

def main(): 
    for t in range(-6, 7): 

     pop1(t) 

    total = 0 
    for t in range(-6, 7): 
     result = pop2(t) 
     total+=result 
     print(t, result) 


    print('Total is', total) 

main() 

Ausgang:

-6 0.002472623156634775 
-5 0.006692850924284857 
-4 0.017986209962091562 
-3 0.04742587317756679 
-2 0.11920292202211757 
-1 0.2689414213699951 
0 0.5 
1 0.7310585786300049 
2 0.8807970779778823 
3 0.9525741268224331 
4 0.9820137900379085 
5 0.9933071490757153 
6 0.9975273768433653 
Total is 6.5 
0

Nach dem Einzug Fixierung, ist hier eine Arbeitsversion:

import math 

def pop1(t): 
    r1 = 1/(1 + (math.e ** -(t))) 
    print(r1) 

def pop2(t): 
    r1 = 1/(1 + (math.e ** -(t))) 
    return r1 

def main(): 
    for t in range(-6, 7): 
     print(t, end=" ") 
     pop1(t) 

    total = 0  
    for t in range(-6, 7): 
     result = pop2(t) 
    total = total + result 
    print(t, result) 

    print('Total is', total) 

main() 

Ausgabe

-6 0.002472623156634775 
-5 0.006692850924284857 
-4 0.017986209962091562 
-3 0.04742587317756679 
-2 0.11920292202211757 
-1 0.2689414213699951 
0 0.5 
1 0.7310585786300049 
2 0.8807970779778823 
3 0.9525741268224331 
4 0.9820137900379085 
5 0.9933071490757153 
6 0.9975273768433653 
6 0.9975273768433653 
Total is 0.9975273768433653