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

时间:2013-10-09 21:17:10

标签: delphi modulo

我在程序中使用此代码,我遇到了第1条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;

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

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

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

我该如何解决这个问题?

1 个答案:

答案 0 :(得分:10)

if测试没有意义:

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

另外,为了理智,最好始终用你的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}

关于编码风格的评论
函数和变量名称应表明其含义。

`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?

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

为什么您的代码不起作用

让我们挑选测试。

if ((i <> 11) or (i mod 11 <> 0)) then
  1. or如果(i&lt;&gt; 11)为真或(i mod 11&lt;&gt; 0)为真,则返回true
  2. (i&lt;&gt; 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语句应该测试积极的东西。