2017-07-14 38 views
0

我是新來的python,並試圖創建一個python3腳本,使用歐幾里德算法找到GCD,但我不斷收到錯誤。Python 3意外的錯誤TypeError

代碼:

firstnum = input("Enter the first number: ") 
secondnum = input("Enter the second number: ") 

if firstnum == secondnum: 
    print("GCD is: {}").format(firstnum) 
    quit() 

if firstnum > secondnum: 
    while True: 
     thirdnum = firstnum % secondnum 
     firstnum = secondnum 
     secondnum = thirdnum 
     if thirdnum == 0: 
      print("GCD is: {}").format(firstnum) 
      quit() 
     else: 
      continue 

if firstnum < secondnum: 
    while True: 
     thirdnum = secondnum % firstnum 
     secondnum = firstnum 
     firstnum = thirdnum 
     if thirdnum ==0: 
      print("GCD is: {}").format(secondnum) 
      quit() 
     else: 
      continue 

錯誤:

Traceback (most recent call last): File "..\Playground\", line 21, in <module> 
    thirdnum = secondnum % firstnum 
TypeError: not all arguments converted during string formatting 

如果有一種方法可以解決這個錯誤,請解釋如何以及爲什麼發生在首位。我也是字符串格式化的新手,所以如果您知道使用變量打印字符串的更有效方式,請告訴我。

回答

1

這個操作實際上是試圖執行字符串格式化

thirdnum = firstnum % secondnum 

如果你試圖執行需要轉換爲int

firstnum = int(input("Enter the first number: ")) 
secondnum = int(input("Enter the second number: ")) 
模運算