Algorithm For-在特定条件下执行的循环

Algorithm For-在特定条件下执行的循环,algorithm,for-loop,Algorithm,For Loop,我有一个for循环,在这个循环中,计数的限制是不同的。代码在循环中每运行5次就调用一个方法,当剩下几次来运行循环时,表示循环将再运行3次并退出,我必须检查该值,然后在代码运行循环的3次中调用该方法 假设n=17 for(int i = 0 ; i < n ; i++){ if(i%5){ call method } // the remaining 2 more times the code run thru this loop i have to call the method

我有一个for循环,在这个循环中,计数的限制是不同的。代码在循环中每运行5次就调用一个方法,当剩下几次来运行循环时,表示循环将再运行3次并退出,我必须检查该值,然后在代码运行循环的3次中调用该方法

假设n=17

for(int i = 0 ; i < n ; i++){
if(i%5){
  call method
 }
 // the remaining 2 more times the code run thru this loop i have to call the method

}
for(int i=0;i

关于如何处理这种情况有什么想法吗?

可以在单一条件下完成。
(i%5==0)
的最后一个i是
5*(n/5)

因此,当
(i%5==0)
i>5*(n/5)
时调用该方法

for(int i=0;i(5*(n/5))){
调用方法
} 
}
在n=17的例子中,n/5=3,因此你调用i=0、5、10和15的方法,然后条件的第二部分开始,你调用i=16的方法(请注意,因为循环在我达到17时退出,所以只剩下1次
,而不是2次)。

for(int i=0;i(n-3)){
//调用方法
} 
}

如果我正确理解了您的问题,这应该允许您在循环中每5次调用一次该方法,以及最后三次调用该方法。

您能对这一部分再解释一下吗“当剩下几次运行循环时,如果说循环将再运行3次并退出,我必须检查该值,然后调用该方法,代码将运行循环3次。”。我不太理解你。
for(int i = 0 ; i < n ; i++){
  if((i%5 == 0) || i > (5*(n/5))) {
    call method
  } 
}
for(int i = 0 ; i < n ; i++) {
   if(i%5 == 0 || i > (n-3)) {
       //call method
   } 
}