2012-08-30 37 views
0

裏面比較變量我有這樣的代碼:A/F環(批)

@echo off 
SETLOCAL ENABLEDELAYEDEXPANSION 

SET /A counter=0 
SET /A counter2=0 

for /f %%h in (users.txt) do (
    set /a counter2=0 
    set /a counter=!counter!+1 

for /f %%i in (users.txt) do (
    set /a counter2=!counter2!+1 
    IF !counter! gtr !counter2! 
      echo !counter! and !counter2! 
    ) 
) 

出於某種原因,我在那裏錯誤的if語句。如果我把它交叉出來,它們都運行得很好。 我的語法有什麼問題? 謝謝!

回答

2

EitanT可能有你正在尋找的解決方案,但它不能完全解釋你的問題。

如果您刪除了IF語句,則會在調整縮進後更好地顯示實際邏輯。第二回路在第一回路內運行。

@echo off 
SETLOCAL ENABLEDELAYEDEXPANSION 

SET /A counter=0 
SET /A counter2=0 

for /f %%h in (users.txt) do (
    set /a counter2=0 
    set /a counter=!counter!+1 

    for /f %%i in (users.txt) do (
    set /a counter2=!counter2!+1 
    echo !counter! and !counter2! 
) 
) 

當你把IF語句中你得到這個代碼不當

@echo off 
SETLOCAL ENABLEDELAYEDEXPANSION 

SET /A counter=0 
SET /A counter2=0 

for /f %%h in (users.txt) do (
    set /a counter2=0 
    set /a counter=!counter!+1 

    for /f %%i in (users.txt) do (
    set /a counter2=!counter2!+1 
    IF !counter! gtr !counter2! 
    echo !counter! and !counter2! 
) 
) 

IF語句是不完整的 - 你沒有告訴它,如果真要做什麼。

如果你想在ECHO成爲IF的一部分,那麼你需要做1 3件事:

1)追加ECHO if語句

IF !counter! gtr !counter2! echo !counter! and !counter2! 


2)使用線繼續打開IF和ECHO線成一個邏輯線路

IF !counter! gtr !counter2!^ 
echo !counter! and !counter2! 


3)添加另一組括號。請注意,左括號必須與IF相同,並且前面必須有一個空格。

IF !counter! gtr !counter2! (
    echo !counter! and !counter2! 
) 


幫助系統描述IF的正確語法。從命令行鍵入HELP IFIF /?以獲得幫助。

注意我發佈的代碼的邏輯與EitanT解決方案不同。我不確定哪個是正確的。像大多數編程語言一樣,縮進不會影響邏輯,它可以讓人們更清楚邏輯是什麼。您的原始縮進顯示了EitanT提供的邏輯。我忽略了縮進並提供了計算機看到的邏輯。

順便說一句 - 你不需要在SET/A語句中展開變量。以下工作正常:

set /a counter=counter+1 

更妙的是,你可以使用增加的賦值操作符:

set /a counter+=1 

SET/A還支持在一條語句中多次轉讓:

set /a counter2=0, counter+=1 

你做不需要在頂部初始化counter2,因爲您也可以在第一個循環中執行它。

下面是使用基於現有的括號,我看到了邏輯最終代碼,忽略你的縮進:

@echo off 
SETLOCAL ENABLEDELAYEDEXPANSION 

SET /A counter=0 

for /f %%h in (users.txt) do (
    set /a counter2=0, counter+=1 

    for /f %%i in (users.txt) do (
    set /a counter2+=1 
    IF !counter! gtr !counter2! echo !counter! and !counter2! 
) 
) 
+0

你是我的英雄人! – JustAGuy

2

我可以當場兩個問題:

1)第一循環for不具有右括號:

for /f %%h in (users.txt) do (
    set /a counter2=0 
    set /a counter=!counter!+1 
) <---------------------------------- You're missing this ")"! 

2)在第二循環中,if語句缺少一個左括號:

IF !counter! gtr !counter2! ( <------ You're missing this "("! 
     echo !counter! and !counter2! 
) 

希望這會有所幫助!

1

if語句應該要麼是全部在一行上,或者包含在()

這裏是一個修正:

@echo off 
SETLOCAL ENABLEDELAYEDEXPANSION 

SET /A counter=0 
SET /A counter2=0 

for /f %%h in (users.txt) do (
    set /a counter2=0 
    set /a counter=!counter!+1 

    for /f %%i in (users.txt) do (
    set /a counter2=!counter2!+1 
    IF !counter! gtr !counter2! (
     echo !counter! and !counter2! 
    ) 
) 
) 

正確的縮進可以幫助您跟蹤包圍錯誤。