嗨我现在制作一个简单的批处理文件,我试图在最后添加正确的答案编号,但它一直说零,因为选择答案时变量值不会改变。这是我的代码
@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语句中更改变量值?
答案 0 :(得分:4)
首先需要set
变量,然后goto
。按照目前的编写,您的脚本首先转到标签yes
。因此,永远不会达到if %ch1%==B set correctn=1
行:
if %ch1%==B goto yesif %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
)