我在python中找到了一个用6修改数字5的程序,但问题是我在python2中得到了它,如果我在python3中更改它并重新运行它,就会产生奇怪的输出。
python 2代码的来源是
http://www.geeksforgeeks.org/replace-0-5-input-integer/
我的完整python3代码是
def convert5to6rec(num):
# Base case for recurssion termination
if(num == 0):
return 0
# Extract the last digit and change it if needed
digit = num % 10
if(digit == 5):
digit = 6
# Convert remaining digits and append the last digit
return convert5to6rec(num/10) * 10 + digit
# It handles 0 to 5 calls convert0to5rec() for other numbers
def convert5to6(num):
if(num == 5):
return 6
else:
return convert5to6rec(num)
# Driver Program
num = 520
print(convert5to6(num))它的输出是170642.43254304124。
有人能指出我留下的那个愚蠢的错误吗?
PS:我需要程序将数字5替换为6。
预期产量应该是620
发布于 2017-10-30 02:27:31
将num/10更改为num//10。在Python3中,使用/运算符进行整数除法会产生一个浮点结果。要获得整数除法,需要使用//运算符。
发布于 2017-10-30 02:27:21
您可以将整数转换为字符串,用6替换5,然后将其转换为整数,而不是进行数学运算。最简单的方法就是
int(str(num).replace('5', '6'))发布于 2017-10-30 02:30:47
它不能在python 3中工作的原因是因为python 2和3中的除法行为不同。在python 2中,/做地板划分,而在python 3中是真正的划分。
所以在python 2中,
In [1]: 11 / 2
Out[1]: 5在python 3,
In [2]: 11/2
Out[2]: 5.5为了在python 3中进行楼层划分,您需要使用//而不是/。因此,您只需要在代码中用/替换//。
https://stackoverflow.com/questions/47007298
复制相似问题