我检查一个数字是另一个数字的倍数的方式有什么问题?

Alb*_*ssi -2 delphi modulo

我在一个过程中使用此代码,我遇到了第一个if子句的麻烦:

procedure TForm1.Button1Click(Sender: TObject);
var i,indice,n,conto:integer;
    a:string;
begin
  indice:=1;
  conto:=0;

  Memo2.Lines.Add('<tr>');

  for i := 1 to 649 do
   begin
    if ((i <> 11) or (i mod 11 <> 0)) then
     begin
      proced4();
     end
    else
     begin
      Memo2.Lines.Add('</tr><tr>');
      proced5();
    end;
   end;
end;
Run Code Online (Sandbox Code Playgroud)

我有一个for,从1到649.当索引是11的倍数时,11, 22, 33, 44...我必须调用

Memo2.Lines.Add('</tr><tr>');
proced5();
Run Code Online (Sandbox Code Playgroud)

使用我编写的代码,只有当索引i为11时,代码才会调用proced5().但是,例如,当i为22或33时,它执行proced4()而不是proced5().

我怎样才能解决这个问题?

Joh*_*ica 10

if测试没有意义:

i mod 11 <<-- will be 0 for any multiple of 11. (including 0) 
(i <> 11)  <<-- superflous, the mod already does the job.
Run Code Online (Sandbox Code Playgroud)

同样为了理智,最好总是让你的if测试积极的东西.
人类不善于解析否定.

  for i := 1 to 649 do begin
    if ((i mod 11) = 0) then begin
      Memo2.Lines.Add('</tr><tr>');
      procedureWithAMeaningfulName5();
    end else {if not multiple of 11 then} begin
      procedureWithAMeaningfulName4();
    end;
  end; {for}
Run Code Online (Sandbox Code Playgroud)

编码样式的注释
函数和变量名称应表明其含义.

`Button1`: bad, what does the button do? Should e.g. `ButtonBuildHTMLTable`  
`proced5`: what the hell does that do?? Give it a meaningful name.  
`indice`: Index of what?
`conto`: count of what?
Run Code Online (Sandbox Code Playgroud)

你的缩进是不一致的; 你知道压力CTRL + D会让Delphi自动缩进你的代码吗?

为什么你的代码不起作用

让我们挑选一下测试.

if ((i <> 11) or (i mod 11 <> 0)) then
Run Code Online (Sandbox Code Playgroud)
  1. or返回true,如果是(i <> 11)为真或(i国防部11 <> 0)为真.
  2. (i <> 11)几乎总是如此,除非i = 11.
  3. 因此,测试B:(i mod 11 <> 0)只有在(i = 11)时才进行测试.
  4. 在所有其他情况下proced4();运行.
  5. 情况i = 22,i = 33等不符合测试not(i <> 11)属性(i = 11),因此不会触发其他.
  6. 注意第5点的双重否定,这就是为什么if语句应该测试积极的东西.