Find centralized, trusted content and collaborate around the technologies you use most.
Teams
Q&A for work
Connect and share knowledge within a single location that is structured and easy to search.
我想为 for 循环的每一秒运行做一些事情。有没有一种很好的方法可以在不使用大量行的情况下做到这一点?
当我们这样做的时候,我更喜欢一个通用的“技巧”,所以每三次或四次做一些事情也是可能的吗?
例子:
for( int i = 0; i < 10; i++ ) { do something; if( i == odd number ) { do something every alternating time; } }
希望你能帮忙。干杯。
每隔 n 次做某事:
if (i % n == 0) …
请注意,这将在第一次、第 n+1 次、第 2n+1 次等迭代时触发。如果要在第 n 次、第 2n 次等触发,请执行以下操作:
if (i % n == n - 1) …
if (i % 2)
奇数为真i,否则为假。如果您愿意,可以1明确比较:
i
1
if (i % 2 == 1)
做某事n的时间是相似的。例如,每 4 次,从1
n
if (i % 4 == 1)