2015-11-05 231 views
-3

我在python中编写了下面的程序来找出两个数字a和b的hcf和lcm。 x是两个数字中较大的一个,y较小,我打算在程序的上半部分找到这两个数字。他们稍后会用于寻找hcf和lcm。但是当我运行它时,它会以红色阴影x。我不明白原因。python程序找到hcf和lcm

a,b=raw_input("enter two numbers (with space in between: ").split() 
if (a>b): 
    int x==a 
else: 
    int x==b 
for i in range (1,x): 
    if (a%i==0 & b%i==0): 
     int hcf=i 
print ("hcf of both is: ", hcf) 
for j in range (x,a*b): 
    if (j%a==0 & j%b==0): 
     int lcm=j 
print ("lcm of both is: ", lcm)   

这个寻找lcm,hcf的算法在c中完美的工作,所以我不觉得应该有算法的问题。这可能是一些语法问题。

+0

你的代码中有语法错误, 很多。请按照初学者的教程。 – Lafexlos

+0

它将a赋值给x,但需要满足条件a> b。 – dreadedHarvester

+1

'int x == a'这不是如何分配工作。即使在C中也没有。 – Lafexlos

回答

0
​​
+2

虽然这可能会提供一个问题的答案,但它有助于提供一些评论,以便其他人可以了解此代码执行其功能的“原因”。请参阅[如何回答](http://stackoverflow.com/help/how-to-answer)了解更多细节/上下文到答案的方法。 –

0

你几乎拥有了正确的,但也有一些Python语法问题,你需要需要工作:

a, b = raw_input("enter two numbers (with space in between: ").split() 

a = int(a) # Convert from strings to integers 
b = int(b) 

if a > b: 
    x = a 
else: 
    x = b 

for i in range(1, x): 
    if a % i == 0 and b % i==0: 
     hcf = i 

print "hcf of both is: ", hcf 

for j in range(x, a * b): 
    if j % a == 0 and j % b == 0: 
     lcm = j 
     break  # stop as soon as a match is found 

print "lcm of both is: ", lcm 

使用Python 2.7.6测试