0
@echo off
pause
set /a x=1
set /a n=0
set /p x_end=x (End)=
:loop
cls
set /a n=n+1
set /a x=x+n+1
set /a students=n+2
echo x=%x%, n=%n%, x (End)=%x_end%
if (%x%=%x_end% goto end)
goto loop
:end
echo Answer: x (End)=%x%, Students=%students%, n (end)=%n%
echo.
echo Click Anything To Exit...
pause > nul
exit

The "if" line is producing a message that what you put in the %x_end% variable "was unexpected this time".

1
  • 1
    Too lazy to check now, but your closing bracket should be before the goto.
    – Daniel B
    Commented Jun 4, 2015 at 15:58

1 Answer 1

0
@echo off
rem pause
set /a x=1
set /a n=0
set /p x_end=x ^(End^)=
rem ensure %x_end% will result to a number 
set /a "x_end=x_end"
:loop
  echo cls
  set /a n=n+1
  set /a x=x+n+1
  set /a students=n+2
  echo x=%x%, n=%n%, x ^(End^)=%x_end%
  rem pause >nul
  if %x% GTR %x_end% goto end
goto loop
:end
echo Answer: x ^(End^)=%x%, Students=%students%, n ^(end^)=%n%
echo(
echo Click Anything To Exit...
pause > nul
rem exit

There are next improvements in above code snippet:

  • merely for debugging purposes
    • some rem (initial pause, final exit);
    • echo cls instead of cls;
  • important
    • set /a "x_end=x_end" to ensure %x_end% will result to a number for whatever user's input;
    • if valid syntax: use GTR (>, greater than) or GEQ (>=, greater than or equal);
    • because of parentheses special meaning in batch scripting, all opening ( and closing ) are escaped in all occurrences where those should be used literally (echo and set /p). Trying if 1==1 (echo (inner) parentheses) will show that it could matter. Although this does not matter in given code snippet, it's worthwhile as a matter of general principle.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .