Truecolor
Truecolor

Reputation: 469

Windows cmd batch file calculation

I have this code which is to divide two numbers from user input. It should exit the program if the user enters the number 999 for either the first or the second number. And if the user enters 0 for the second number, then it should ask the user to enter a non zero number. My problem is that when I enter two good numbers, I don't get any output. It just shows "Press any key to continue..." and then exits the whole terminal once I press any key. Any help would be really appreciated.

:MAIN
cls
echo.
SET /p num1="Please enter the first number: "
if %num1%==999 GOTO EOF
cls

:SECOND_NUM
SET /p num2="Please enter the second number: "
if %num2%==999 GOTO EOF
if %num2%==0 GOTO ERROR
echo.
GOTO DIVISION

:DIVISION
SET /A result = %num1% / %num2%
echo The answer of %num1% divided by %num2% = %result% >> results.txt
pause
exit
GOTO CONTINUE



:ERROR
echo Error! Cannot divide by 0 (zero). Enter a non zero second number, please.
GOTO SECOND_NUM


:CONTINUE
echo To Exit the program, please enter 999
GOTO MAIN
echo.
pause 
EXIT

Upvotes: 2

Views: 1604

Answers (1)

Potato Head
Potato Head

Reputation: 143

I noticed a couple of things especially in these sections.

:MAIN
cls
echo.
SET /p num1="Please enter the first number: "
if %num1%==999 GOTO EOF
cls

:SECOND_NUM
SET /p num2="Please enter the second number: "
if %num2%==999 GOTO EOF
if %num2%==0 GOTO ERROR
echo.
GOTO DIVISION

:DIVISION
SET /A result = %num1% / %num2%
echo The answer of %num1% divided by %num2% = %result% >> results.txt
pause
exit
GOTO CONTINUE

Now in these %num2%==999 GOTO EOF I believe the proper way to exit the batch file with the End Of File GOTO is GOTO :EOF, notice the semicolon. Otherwise it'll say something like couldn't find the path, and it'll exit anyways. Here, echo The answer of %num1% divided by %num2% = %result% >> results.txt all you're telling the batch file to do is to redirect the output to the results.txt by >> results.txt, so if you wanted to display the text, just remove that little chunk. and finally, right after the pause, where you're wanting to display the calculation, before you tell the file where to goto, you included an exit so the batch file exits.


Edit Here's how I would do your entire batch file. I moved a few things around, got rid of some, added some.

@ECHO OFF
COLOR 0A

:CONTINUE
CLS
ECHO.
SET /P X=Do you wish to divide? [Y/N] 
IF /I %X% EQU Y (GOTO :MAIN) ELSE (GOTO :EOF)

:MAIN
CLS
ECHO.
SET /p num1="Please enter the first number: "

:SECOND_NUM
CLS
ECHO.
SET /p num2="Please enter the second number: "
IF "%num2%" EQU "0" GOTO :ERROR

:DIVISION
CLS
ECHO.
SET /A result=%num1% / %num2%
ECHO The answer of %num1% divided by %num2% = %result%
ECHO The result of %num1% divided by %num2% = %result% >> results.txt
PAUSE
GOTO :CONTINUE

:ERROR
CLS
ECHO.
ECHO Error! Cannot divide by 0 (zero). Enter a non zero second number, please.
PAUSE
GOTO :SECOND_NUM

Upvotes: 1

Related Questions