首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >C++算法到Python

C++算法到Python
EN

Stack Overflow用户
提问于 2021-02-23 01:21:15
回答 2查看 67关注 0票数 1

大家好,所以今天我决定开始学习Python。我在学校学习c++,并用c++编程了大约一年,所以我想开始编写从c++到python的基本算法是一个很好的想法。我想在python中编写最大的公约数,但它给了我这个错误:

代码语言:javascript
复制
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

代码如下:

代码语言:javascript
复制
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))
EN

回答 2

Stack Overflow用户

发布于 2021-02-23 01:25:24

input()提供了一个字符串。您需要使用a = int(input())b = int(input())

票数 2
EN

Stack Overflow用户

发布于 2021-02-23 01:28:38

您所做的是,您已经将a和b的输入作为字符串类型,但是您将它们视为一个整数。因此,您需要在接受输入时对字符串进行类型转换。请参考以下代码:

代码语言:javascript
复制
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))
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/66320403

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档