C++;Python的算法
您好,今天我决定开始学习Python。我在学校学习C++,在C++编程大约1年,所以我认为从C++到Python开始编写基本算法是个好主意。我想用python编写最大公约数,但它给了我以下错误:C++;Python的算法,python,python-3.x,Python,Python 3.x,您好,今天我决定开始学习Python。我在学校学习C++,在C++编程大约1年,所以我认为从C++到Python开始编写基本算法是个好主意。我想用python编写最大公约数,但它给了我以下错误: File "d:\proiecte\c++ to python algorithms\cmmdc.py", line 12, in <module> print(cmmdc(a,b)) File "d:\proiecte\c++ to 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
input()
给出一个字符串。您需要使用a=int(input())
和b=int(input())
input()
给出一个字符串。您需要使用a=int(input())
和b=int(input())
您所做的是,您将a和b的输入作为字符串类型,但将它们作为整数处理。因此,在进行输入时,需要对字符串进行类型转换。请参阅以下代码:
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))
您所做的是,将a和b的输入作为字符串类型,但将它们视为整数。因此,在进行输入时,需要对字符串进行类型转换。请参阅以下代码:
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))
你可能想把你的输入转换成int。int(input())应该有效吗?非常感谢:)你可能想把你的输入转换成int。int(input())应该有效吗?非常感谢:)非常感谢:)非常感谢:)