2016-10-13 3 views
-1

reagiert die If-Anweisung nicht. Ich versuche, die gcd(20,6) die Programmausgaben zu erhalten: gcd(20,6): 20=6(4) + -3, ich brauche es, wenn die letzte Zahl (-3) kleiner als 0 ist, sollte das Programm 20=6(3) + 3 ausgeben, aber die if-Anweisung reagiert nicht. DankWenn die Anweisung nicht antwortet (Python)

rnumtup = (20, 6) 
if rnumtup[0] > rnumtup[1]: 
    x= rnumtup[1] 
    y =rnumtup[0] 
w = x/y 
w = round(w) 
z = x - (y*w) 
z = round(z) 

while z != 0: 
    x = y 
    y = z 
    w = x/y 
    w = round(w) 
    z = x - (y*w) 
    z = round(z) 
    if z > 0: #not responding 
     #some statements 
    if z < 0: #not responding 
     #some statements 
+7

Und was 'wenn z == 0'? –

+0

z kann gleich 0 sein, nichts weniger als das – jack

+0

das ist python 3.5 – jack

Antwort

0

z gleich 0, so dass Ihre if Aussagen nichts zu tun.

Erklärung im Code kommentiert

rnumtup = (20, 6) 
if rnumtup[0] > rnumtup[1]: 
    x= rnumtup[1] #x = 20 
    y =rnumtup[0] #y = 6 
w = x/y #w = 3 
w = round(w) # Does nothing 
z = x - (y*w) # z = 2 
z = round(z) # Does nothing 

while z != 0: 
    x = y # x = 6 
    y = z # y = 2 
    w = x/y # w = 3 
    w = round(w) # Does nothing 
    z = x - (y*w) # z = 0 --> If statements don't work, while loop ends after first iteration 
    z = round(z) 
    if z > 0: #not responding, because z == 0 
     #some statements 
    if z < 0: #not responding, because z == 0 
     #some statements 

Beachten Sie, dass in Python 20/63 gleich, aber 20.0/6 gleich 3.33333..

+0

w = rund() ist für Zahlen, die eine Zahl mit einem Dezimalpunkt ergeben, zB x = 888, y = 54, dann w = 16.4 – jack

+1

Ja, deshalb tut es nichts. 20/6 ist 3, NICHT 3.33, wie Sie erwarten würden. –

+0

@ Gábor Erdős wie das OP sagte Python 3.5, '20/6' ist 3,33. '20 // 6' ist 3 – Jeon

0

Sie würden denken, dass z nicht 0 sein kann, weil der

while z!=0: 

aber wenn Ihr Programm die Anweisung

erreicht
z= round(z) 

z 0 sein können und Sie prüft programmieren nur für streng positive oder negative Zahlen seit 0> 0 falsch ist, eine bessere gdc Funktion euclid's algorithm wäre, hier ist die Python-3-Version

def gdc(a,b): 
    while a!=b: 
     if a>b: 
     a=a-b 
     else: 
     b=b-a 
    return a 
print(gdc(20,6)) 
0

I fand eine Alternative, danke Jungs :)

rnumtup = (20, 6) 
if rnumtup[0] > rnumtup[1]: 
    x= rnumtup[1] 
    y =rnumtup[0] 
w = x/y 
w = round(w) # Does nothing 
z = x - (y*w) 
z = round(z) 

if z< 0: 
    w = x/y 
    w = round(w) 
    w = w-1 
    z = x - (y*w) 
    z = round(z) 

while z != 0: 
    x = y # x = 6 
    y = z # y = 2 
    w = x/y # w = 3 
    w = round(w) # Does nothing 
    z = x - (y*w) 
    if z< 0: 
     w = x/y 
     w = round(w) 
     w = w-1 
     z = x - (y*w) 
    z = round(z)