【问题标题】:Why is my program not running through the first while loop?为什么我的程序没有通过第一个 while 循环运行?
【发布时间】:2017-03-13 03:50:24
【问题描述】:

我正在尝试编写一个代码来计算长除法问题的总进位。这是我为进位编写的函数。我相信我们的问题是第一个 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

【问题讨论】:

  • 您是否尝试访问县 [-index1] 行中的负索引?您在这里面临的实际问题是什么?顺便问一下 x 和 y 是什么?你真正想做什么?
  • x 和 y 是我用长乘法相乘的两个数字,例如 9929 和 129。我只是好奇为什么它计算 9 x 9929 的进位但不继续使用 129 中的 2 和 1。希望这是有道理的,如果需要,我可以随时发布提示
  • 对不起,我不清楚你的解释。您能解释一下您在帖子中所说的“计算长除法问题的总进位数”是什么意思吗?
  • 好吧,给出的例子是:当两个数字相乘时,如果乘积大于 9,则有进位(例如,6 × 4 = 24,其中 2 是进位数字)。
  • 感谢您的解释。我在下面发布了答案。顺便说一句,你编写了不必要的大代码,你可以用更简单的方式解决这个问题。

标签: function python-3.x loops while-loop


【解决方案1】:

我发现了问题。只需在外部 while 循环中初始化变量 index = 1,如下所示。

while (index1 <= county1):
    sum3 = county[-index1]
    index = 1
    while (index <= count):
        sum2 = countx[0-index]
        sum4 = int(sum2)
        ................
        ................

请改进您的编码风格,使代码更具可读性。我花了很长时间才找到问题,因为很难理解您在每个语句中写的内容。

【讨论】:

  • 谢谢你,我为乱码道歉
猜你喜欢
  • 1970-01-01
  • 2019-09-16
  • 1970-01-01
  • 2012-11-03
  • 2021-10-16
  • 2019-11-08
  • 2019-11-08
  • 2011-09-08
  • 1970-01-01
相关资源
最近更新 更多