首页 > 解决方案 > Guessing game with only 10 tries in batch

问题描述

I'm trying to make this guessing game with only 10 tries in batch but whatever number I guess it says the number is smaller and I can't find the problem

set /a var=%random%
echo %var%
for /l %%x in (1, 1, 10) do (

set /p guess="Try to guess the number: "
if "%guess%" equ "%var%" (goto 1)
if "%guess%" gtr "%var%" (echo Your number is greater)
if "%guess%" lss "%var%" (echo Your number is smaller)

)

echo You lost
pause
exit
:1
echo you guessed the number

标签: batch-file

解决方案


Maybe you have missed the code: SETLOCAL ENABLEDELAYEDEXPANSION.

And while comparing the size of the number, it is not necessary to use quotes.


Or if you don't wish to use it, you can make a more complicated loop.

@echo off
set /a var=%random%
rem I don't know why you would add the next line but I'll still let it stay there.
echo %var%
set l=0
goto guess

:guess
set /a l=l+1
set guess=-1
set /p guess="Try to guess the number: "
if %guess% equ %var% (goto correct)
if %guess% lss 0 (echo The input should be an integer which is not less than 0)
if %guess% gtr %var% (echo Your number is greater) else (echo Your number is smaller)
if "%l%" == "10" (goto fail) else (goto guess)

:fail
echo You lost
pause
exit

:correct
echo you guessed the number
pause
exit

推荐阅读