大家好,所以今天我决定开始学习Python。我在学校学习c++,并用c++编程了大约一年,所以我想开始编写从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 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))发布于 2021-02-23 01:25:24
input()提供了一个字符串。您需要使用a = int(input())和b = int(input())。
发布于 2021-02-23 01:28:38
您所做的是,您已经将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))https://stackoverflow.com/questions/66320403
复制相似问题