嵌套循环与变量

huangapple go评论107阅读模式
英文:

Nested Loop with variables

问题

我正在尝试在内部的 j 循环中打印一个值。然而,我的 j 循环不起作用。我不确定是什么原因导致它不起作用,因为我已经尝试了各种可能的方法来使它能够在 j 循环中打印值。

我该如何使这个循环正常工作?

英文:

I am trying to print a value inside the j(innermost) loop. However,my j loop is not working. I am not sure what's causing it as I tried every possible way to make it work to print values in j
loop.

How can I make the loop work ?

答案1

得分: 1

左边界始终大于右边界的内循环。您可以交换它们,或者如果您真的想要从大到小迭代,可以在 range 中使用负步骤。

现在您的步骤是正数,等于 2

以下是我是如何解决这个问题的:

  1. m = 961
  2. n = 220
  3. for i in range(1-1, m-3):
  4. #print ("test: i loop is working")
  5. print((2*n*(i+5)-1), (2*n*(i+1)-5))
  6. for j in range((2*n*(i+5)-1), (2*n*(i+1)-5), -2):
  7. print ("test: j is not working")

输出(截断):

  1. 2639 875
  2. 3079 1315
  3. 3519 1755
  4. 3959 2195
  5. 4399 2635
  6. 4839 3075
  7. 5279 3515
  8. 5719 3955
  9. ...
英文:

Well, left border of inner loop is always greater than right one. You can either swap them or use a negative step in range if you really want to iterate from greater to smaller.

Right now your step is positive and equals 2.

Here's how I figured it out:

  1. m = 961
  2. n = 220
  3. for i in range(2-1, m-3):
  4. #print ("test: i loop is working")
  5. print((2*n*(i+5)-1), (2*n*(i+1)-5))
  6. for j in range((2*n*(i+5)-1), (2*n*(i+1)-5),2):
  7. print ("test: j is not working")

Output (truncated):

  1. 2639 875
  2. 3079 1315
  3. 3519 1755
  4. 3959 2195
  5. 4399 2635
  6. 4839 3075
  7. 5279 3515
  8. 5719 3955
  9. ...

huangapple
  • 本文由 发表于 2023年7月5日 01:18:44
  • 转载请务必保留本文链接:https://go.coder-hub.com/76614741.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定