2013-10-09 23 views
-2

我在一個過程中使用這個代碼,我有與所述第一煩惱如果子句:我的方法檢查數字是另一個數字的倍數有什麼問題?

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; 

我有一個爲前進1至649.當指數是11 11, 22, 33, 44...倍數我必須致電

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

隨着我寫的代碼,只有當索引i是11時代碼調用了程序5()。但是,例如,當我是22或33時,它執行的是程序4()而不是程序5()。

我該如何解決這個問題?

+0

好吧,但這並沒有解決我的問題。 –

+0

你需要解決什麼問題? –

+0

用我寫的代碼,只有當索引i是11時,代碼纔會調用'程序5()'。但是,例如,當我是22或33時,它執行'程序4()'而不是'程序5()'。 –

回答

10

if測試沒有意義:

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

也爲理智最好是總是有你的,如果來測試一些積極的。
人類在分析否定時不好。

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返回true如果是(i <> 11)爲真或(i國防部11 <> 0)爲真。
  2. (ⅰ<> 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點的雙重否定,這就是爲什麼如果陳述應該測試正面的東西。
+0

這是完美的,現在我的代碼工作。會接受和+1 –

+0

我不認爲Ctrl + D在舊版本上工作。是否推出了D2010 AitoIndent? –

相關問題