我在程序中使用此代码,我遇到了第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()。
我该如何解决这个问题?
答案 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
or
如果(i&lt;&gt; 11)为真或(i mod 11&lt;&gt; 0)为真,则返回true
。 (i mod 11 <> 0)
只有在(i = 11)时才会被测试。 proced4();
运行。 not(i <> 11)
又名(i = 11)
,因此不会触发其他。