Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/r/71.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
R 循环使用while而不打印所有迭代_R_Loops_While Loop_Each - Fatal编程技术网

R 循环使用while而不打印所有迭代

R 循环使用while而不打印所有迭代,r,loops,while-loop,each,R,Loops,While Loop,Each,如何使用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 而(i

如何使用
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
而(i<300){
如果(i/20==整数){
印刷品(一)
}
i=i+1
soma_300=soma_300+i
}
索马尤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
  }
}
soma_300=0
i=0
c=0
而(i<300){
i=i+1
soma_300=soma_300+i
c=c+1
如果(c==20){
印刷品(一)
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
soma_300=0
i=0
而(i<300){
如果(i%%20==0){
印刷品(一)
}
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
sum=0
i=0
而(i<300){
如果(i%%20==0){
印刷品(一)
}
i=i+1
sum=sum+i
}
总和

您使用的是什么语言?对不起!我用的是R,谢谢!