簡體   English   中英

C++ 算法到 Python

[英]C++ algorithms to Python

你好所以今天我決定開始學習Python。 我正在學校學習 c++ 並在 c++ 編程大約 1 年,所以我認為開始編寫從 c++ 到 Z65DDBZ6.79437BDD7 的基本算法是一個好主意我想在 python 中寫出最大公約數,但它給了我這個錯誤:

File "d:\proiecte\c++ to python algorithms\cmmdc.py", line 12, in <module>
    print(cmmdc(a,b))
  File "d:\proiecte\c++ to python algorithms\cmmdc.py", line 7, in cmmdc
    return cmmdc(b, a % b)
TypeError: not all arguments converted during string formatting

這是代碼:

print ("alorithm to solve gcd from c++ to python! ")

def cmmdc(a, b):
    if b == 0:
        return a
    else:
        return cmmdc(b, a % b)
print ("write the first number: ")
a = input()
print ("write the second number: ")
b = input()
print(cmmdc(a,b))

input()給出一個字符串。 您需要使用a = int(input())b = int(input())

您所做的是,您將 a 和 b 的輸入作為字符串類型,但您將它們視為 integer。 因此,您需要在輸入時對字符串進行類型轉換。 參考下面的代碼:

print ("alorithm to solve gcd from c++ to python! ")

def cmmdc(a, b):
    if b == 0:
        return a
    else:
        return cmmdc(b, a % b)
print ("write the first number: ")
a = int(input())    #type casting the string input into integer.
print ("write the second number: ")
b = int(input())
print(cmmdc(a,b))

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM