我试图编写一个代码来计算长除法问题的总数。这是我为这些载体写的功能。我相信我们的问题是第一个while循环不能一直运行。如果是这样,为什么呢?这是在Python 3.5中。
carries = 0
sum1 = 0
countx = str(x)
county = str(y)
countx1 = len(countx)
county1 = len(county)
countx2 = int(countx1)
county2 = int(county1)
carry_over = 0
count = countx1
index = 1
index1 = 1
carrieslist = [0,0,0,0,0,0,0,0,0,0]
while (index1 <= county1):
sum3 = county[-index1]
while (index <= count):
sum2 = countx[0-index]
sum4 = int(sum2)
sum5 = int(sum3)
sum1 = sum4*sum5+carry_over
sum6 = str(sum1)
index = index+1
if (sum1 > 9):
carries += 1
carry_over = int(sum6[0])
if carry_over > 0:
if carry_over == 1:
carrieslist[1] += 1
if carry_over == 2:
carrieslist[2] += 1
if carry_over == 3:
carrieslist[3] += 1
if carry_over == 4:
carrieslist[4] += 1
if carry_over == 5:
carrieslist[5] += 1
if carry_over == 6:
carrieslist[6] += 1
if carry_over == 7:
carrieslist[7] += 1
if carry_over == 8:
carrieslist[8] += 1
if carry_over == 9:
carrieslist[9] += 1
else:
carry_over = 0
index1 = index1 + 1
print(" ")
print("Carries:",carries)
print(" ")
if sum(carrieslist) > 0:
print("Carry digit --> Frequency")
countlist = 0
indexlist = 0
while (countlist < len(carrieslist)):
if (carrieslist[indexlist] > 0):
print(indexlist,"-->",carrieslist[indexlist])
indexlist += 1
countlist += 1
else:
indexlist += 1
countlist += 1
答案 0 :(得分:1)
我发现了问题。只需在外部while循环中初始化变量index = 1,如下所示。
while (index1 <= county1):
sum3 = county[-index1]
index = 1
while (index <= count):
sum2 = countx[0-index]
sum4 = int(sum2)
................
................
请改进您的编码风格,以使代码更具可读性。我花了很多时间才发现问题,因为很难理解你在每个陈述中所写的内容。