2017-09-04 157 views
0

嗨,我現在做簡單的批處理文件,我試圖在最後添加正確的答案編號,但它一直說零,因爲當選擇答案時變量值不會改變。這裏是我的代碼如下如何設置變量值如果

@echo off 
title Game One 
color 1f 
::############################# 
:one 
set correctn=0 
set correctn2=0 
cls 
echo What is 2 + 2? 
echo. 
echo. 
echo A) 6 
echo B) 4 
echo C) 49 
echo D) 17 
echo. 
echo. 
echo Type the correct answer. 
set /p ch1= 
echo. 
echo. 
if not defined ch1 (goto one) 
if %ch1%==A goto no 
if %ch1%==A correctn=0 
if %ch1%==B goto yes 
if %ch1%==B correctn=1 
if %ch1%==C goto no 
if %ch1%==C correctn=0 
if %ch1%==D goto no 
if %ch1%==D correctn=0 
pause>null 
::######################################### 
:no 
cls 
echo Sorry, that answer is incorrect. 
echo. 
echo. 
echo The correct choice was B, which was 4. 
pause>null 
goto two 
::######################################### 
:yes 
cls 
echo You are correct. Congratulations. 
echo Press any key to continue. 
pause>null 
goto two 
::########################################## 
:two 
cls 
echo What is 100 divided by 2? 
echo A) 45 
echo B) 50 
echo C) 90 
echo D) 17 
echo. 
echo. 
set/p ch2= 
echo. 
echo. 
if not defined ch2 (goto two) 
if %ch2%==A goto no2 
if %ch2%==A correctn2=0 
if %ch2%==B goto yes2 
if %ch2%==B correctn2=1 
if %ch2%==C goto no2 
if %ch2%==C correctn2=0 
if %ch2%==D goto no2 
if %ch2%==D correctn2=0 
echo Invalid Choice, Please Try Again! 
pause>null 
::################################# 
:no2 
cls 
echo Sorry, that answer is incorrect. 
echo. 
echo. 
echo The correct choice was B, which was 50. 
pause>null 
::######################################## 
:yes2 
cls 
echo You are correct. Congratulations. 
echo Press any key to continue. 
pause>null 
goto end 
::###################################### 
:end 
set/a correct=%correctn% + %correctn2% 
echo Number of answers correct was %correct% 
pause>null 

那麼如果如果已經變量存在if語句如何更改變量值?

+2

你缺少** *設置*關鍵字。 EG使用**如果%ch1%== A set correctn = 0 ** –

+0

沒有抱歉,我試過了,但沒有奏效。但是我做了一些讓它工作的東西,問題是我的if,我改變它,以便它在下一頁之前設置值。但是你幫我弄清楚了這一套 –

回答

4

您需要先變量然後goto。正如目前所寫,您的腳本首先轉到標籤yes。因此,if %ch1%==B set correctn=1線從未達到:

 

            
 
  
             if %ch1%==B goto yes
            
  
if %ch1%==B set correctn=1 
if %ch1%==B goto yes 

此外,IF command字符串比較是大小寫敏感而不/I開關;請嘗試以下操作:

if /I %ch1%==B (set correctn=1&goto yes) 

我使用建議(Windows自帶)CHOICE.EXE代替set /p單個按鍵的用戶輸入,例如如下:

CHOICE /C abcd 
IF %errorlevel%==2 (
    set correctn=1 
    goto yes 
) else (
    set correctn=0 
    goto no 
)