我在python中发现了一个用6来改变数字5的程序,但问题是我在python2中得到了它,如果我在python3中改变它并重新运行它,它会给出奇怪的输出。你知道吗
python2代码的源代码是
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
有人能指出我留下的那个愚蠢的错误吗
我需要程序把数字5换成6。你知道吗
预期产量应为620
将
num/10
更改为num//10
。在python3中,使用/
运算符进行整数除法生成浮点结果。要获得整数除法,需要使用//
运算符。你知道吗它在python3中不起作用的原因是python2和python3中除法行为的不同。在python2中,
/
进行楼层划分,而在python3中,它是真正的划分。你知道吗所以在python 2中
在Python3中
要在python3中进行楼层划分,需要使用
//
而不是/
。所以,您只需要在代码中用//
替换/
。你知道吗您可以将整数转换为字符串,用6替换5,并将其转换回整数,而不必从数学上进行处理。最简单的方法是
相关问题 更多 >
编程相关推荐