|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
- #1. 写一个函数get_digits(n),将参数n每个位置的数字分解出来并按顺序存放到列表中。
- #举例:get_digits(12345) ==> [1, 2, 3, 4, 5]
- def length(n):
- str1 = str(n)
- global length1
- length1 = len(str1)
- return length1
- def get_digits(n):
- if length1 == 1:
- return [n]
- else:
- for i in range(1, length1 + 1):
- #将 n 中的每一位数取出来
- list1.append(n // (10 ** (i - 1) % 10))
- list1.reverse()
- return list1
- list1 = []
- n = int (input ("请输入一个整数:"))
- length(n)
- result = get_digits(n)
- # %s 可以接收任意类型的值
- print ("%d --> %s" %(n, result))
复制代码
运行结果如图,说的是除以0了 但是检查了一下没有发现除以0啊 开始第一次循环就是1
本帖最后由 Twilight6 于 2020-8-1 23:27 编辑
你的代码可以在 for 循环里面测试下 (10 ** (i - 1) % 10) 的值,会发现第二次就为 0 了
改成 ((n //10 ** (i - 1)) % 10) 这样就好了:
- #1. 写一个函数get_digits(n),将参数n每个位置的数字分解出来并按顺序存放到列表中。
- #举例:get_digits(12345) ==> [1, 2, 3, 4, 5]
- def length(n):
- str1 = str(n)
- global length1
- length1 = len(str1)
- return length1
- def get_digits(n):
- if length1 == 1:
- return [n]
- else:
- for i in range(1, length1 + 1):
- #将 n 中的每一位数取出来
- list1.append((n //10 ** (i - 1)) % 10)
- list1.reverse()
- return list1
- list1 = []
- n = int (input ("请输入一个整数:"))
- length(n)
- result = get_digits(n)
- # %s 可以接收任意类型的值
- print ("%d --> %s" %(n, result))
复制代码
|
-
|