数字反转程序迭代异常:输入12345仅交换首尾数字
问题分析与修复
代码中的错误点
- 变量名错误:循环遍历的
theNum2未定义,实际应该用之前转换好的theNumInString,这会导致运行报错,需修正变量名。 - 交换次数计算错误:
numofSwaps = len(myList) % 2是核心问题。这个计算只会得到0或1,输入长度为5的数字时仅执行1次首尾交换,完全达不到全反转效果。正确的交换次数应为列表长度的一半,即len(myList) // 2,这样能保证从两端到中间的所有对应位置都完成交换。
修复后的代码
def swapPositions(list, pos1, pos2): list[pos1], list[pos2] = list[pos2], list[pos1] # 简化交换逻辑 myList = [] theNum = int(input("enter the value")) theNumInString = str(theNum) # 修正变量名错误 for char in theNumInString: myList.append(char) # 修正交换次数计算 numofSwaps = len(myList) // 2 posi1 = 0 posi2 = len(myList) - 1 while numofSwaps != 0: swapPositions(myList, posi1, posi2) posi1 += 1 posi2 -= 1 numofSwaps -= 1 number = "".join(myList) print(number)
更简洁的实现方式
Python中实现数字反转不需要复杂的交换逻辑,直接利用字符串切片就能一步完成:
theNum = int(input("enter the value")) print(str(theNum)[::-1])
如果需要处理负数反转(比如输入-123输出-321),可以额外判断符号:
theNum = int(input("enter the value")) if theNum < 0: reversed_num = -int(str(-theNum)[::-1]) else: reversed_num = int(str(theNum)[::-1]) print(reversed_num)
内容的提问来源于stack exchange,提问作者bernatt.04
相关产品推荐
相关产品推荐

