没有得到预期的输出:在循环

时间:2018-03-05 06:15:09

标签: python-3.x

当输入为245时,它应该给出200 40 5.Its给出0 45无限次。代码错误

    input1=int(input("Enter num "))
    n=len(str(input1))
    while(n>=1):
       unit_place=10**(int(n)-1)
       div=int(input1/unit_place)
       rem=input1%unit_place
       print(div*unit_place,rem)
       input1=rem

3 个答案:

答案 0 :(得分:2)

对您的代码进行一些清理:

代码:

input1=int(input("Enter num "))
n = len(str(input1))
results = []
while n > 1:
    unit_place = 10 ** (int(n) - 1)
    div, rem = divmod(input1, unit_place)
    results.append(div * unit_place)
    input1 = rem
    n = len(str(input1))
results.append(rem)
print(results)

245的结果:

[200, 40, 5]

答案 1 :(得分:1)

使用以下代码:

input1=int(input("Enter num "))
n=len(str(input1))
while(n>=1):
   unit_place=10**(int(n)-1)
   div=int(input1/unit_place)
   rem=input1%unit_place
   print(div*unit_place,rem)
   input1=rem
   n -=1

输出:

Enter num 123
100 23
20 3
3 0

如果您想以您提到的方式输出输出,请使用:

input1=int(input("Enter num "))
n=len(str(input1))
while(n>=1):
   unit_place=10**(int(n)-1)
   div=int(input1/unit_place)
   rem=input1%unit_place
   print(div*unit_place, end =" ")
   input1=rem
   n -=1

输出:

Enter num 123
100 20 3

答案 2 :(得分:0)

input1=int(input("Enter num "))
n=len(str(input1))
list=[]
print("div*unit_place |","rem")
while(n>=1):
  unit_place=10**(int(n)-1)
  div=int(input1/unit_place)
  rem=input1%unit_place
  list.append(div*unit_place)
  print(str(div*unit_place)+" |",rem)
  input1=rem
  n=int(n)-1
print(list)

输出

Enter num  245
div*unit_place | rem
200            | 45
40             | 5
5              | 0
[200, 40, 5]