if语句没有响应(python)

时间:2016-10-13 15:05:25

标签: python

if语句没有响应。我试图获得gcd(20,6) 程序输出:gcd(20,6): 20=6(4) + -3,我需要它,如果最后一个数字(-3)小于0,程序应输出20=6(3) + 3,但if语句不响应。< / p>

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

3 个答案:

答案 0 :(得分:0)

z等于0,因此您的if语句无法执行任何操作。

代码注释中的说明

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

请注意,在python 20/6中等于3,但20.0/6等于3.33333..

答案 1 :(得分:0)

你会认为z因

而不能为0
while z!=0:

但是当你的程序到达声明时

z= round(z)

z可以为0并且您只对严格正数或负数进行编程检查,因为0> 0为假,更好的gdc函数为euclid's algorithm,这里是python 3版本

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

答案 2 :(得分:0)

我想出了另一种选择,谢谢你们:)

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)