循环 while without 打印所有迭代

loop with while without to print all iterations

如何使用 while 进行循环以计算总和 1 + 2 + 3 + ... + 300,并仅每 20 次迭代打印一次结果。

我尝试构建以下命令,但它不起作用:

soma_300=0
i=0
while(i< 300){
  if (i/20 == integer) {
    print(i)
  }
  i=i+1

  soma_300=soma_300+i
}
soma_300

我想你可以尝试使用另一个像这样的计数器

soma_300=0
i=0
c=0
while(i< 300) {
  i=i+1
  soma_300=soma_300 + i
  c=c+1
  if (c == 20) {
    print(i)
    c = 0
  }
}

您想检查 i 除以 20 的其余部分是否为 0。为此,您需要使用 %%.

soma_300=0
i=0

while(i < 300){
  if (i %% 20 == 0) {
    print(i)
  }
  i=i+1

  soma_300=soma_300+i
}
[1] 0
[1] 20
[1] 40
[1] 60
[1] 80
[1] 100
[1] 120
[1] 140
[1] 160
[1] 180
[1] 200
[1] 220
[1] 240
[1] 260
[1] 280

我不熟悉 R,但您可以尝试使用模数运算符 %%
这似乎有效:

sum = 0
i = 0

while(i < 300) {
  if (i %% 20 == 0) {
    print(i)
  }
  i = i + 1

  sum = sum + i
}
sum