使用"mod"运算符

Jef*_*eff 2 delphi math integer modulo

每当我需要在我的for循环中每300次迭代做一次特定动作时,我试图显示(有意义吗?)

这是代码中我想要做的,但不是我想要的方式:

for I := 0 to 2000 do
  Begin
   if I = 300 then
   DoAnAction;

   if I = 600 then
   DoAnAction

   if I = 900 then
   DoAnAction

   if I = 1200 ......... Same action all over, but I don't want to check all those conditions!
  End;
Run Code Online (Sandbox Code Playgroud)

所以我被告知要使用mod运算符,这就是我的工作方式:

for I := 0 to 2000 do
 Begin
  if I mod 300 = 299 then
  DoAnAction;
 End;
Run Code Online (Sandbox Code Playgroud)

但是,使用上述代码片段的结果将在299,599,899执行操作....

如何使用Mod操作符在300,600,900 ......进行操作?(而且做得if I mod 300 = 300不好)

谢谢!

Kro*_*ica 10

for I := 0 to 2000 do
 Begin
  if (I mod 300 = 0) and (I > 0) then
    DoAnAction;
 End;
Run Code Online (Sandbox Code Playgroud)

虽然你以前的版本确实有意义,但我= 299是第300遍;)

编辑:I mod 300 = 300不起作用,因为mod运算符返回devision的剩余部分,根据定义,它将在范围内0..299

  • @Jeff:如果您担心这种优化水平,请不要.相反,将循环更改为从1到2000`运行,并且当计数器为"0"时它永远不会运行. (2认同)