2015-11-05 228 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測試