Have I done something wrong or why this isn't working? I am quite new with batch. It says "The syntax of the command is incorrect."
if %nm1% lss %nm2% (
echo voitit:%voitat%
set /p "tupla=Voitonmaksu.1 tuplaus.2 (1/2)."
)
if %nm1%==%nm2% (
set /a voitat=%voitat% / 2
echo voitit:%voitat%
set /a voitot=%voitot% + %voitat%
pause
goto peli
)
if %nm2% lss %nm1%(
echo voitit:0
pause
goto peli
)
if %tupla%==1 (
set /a voitot=%voitot% + %voitat%
pause
goto peli
)
if %tupla%==2 goto tuplaus
set /a voitat=%voitat% / 2
set /a voitot=%voitot% + %voitat%
These commands won't work as expected because of delayedexpansion (many many SO articles on this - use the search facility in the top bar)
BUT since you are using set/a - the syntax allows the variables to be expressed "nude" - without the % delimiters, when the delayedexpansion quirk becomes irrelevant (but you should read up on it anyway - to obviate the inevitable follow-up question.)
if %nm2% lss %nm1%(
There must be a space between %nm1% and (
If either argument is non-numeric (probably not, given their names) then the arguments must be "quoted" (applies to any if where the arguments may contain spaces)
Related
What is supposed to happen is that you input a number between 1 and 1,048,567. The program checks if your input is actually a number between 1 and 1,048,567. If your input is a valid number then it will continue onto the next bit of code. If the input is invalid then it will display a message saying it is invalid then loop back and ask you for input again.
When I run this however, I input anything and it says invalid input even if I did input a number between 1 and 1,048,567.
Code:
:setup
#echo off
title Pokemon Shiny Sim
set delay = nul
set count = 0
set chance = 4096
:settings
:setChance
cls
echo Set shiny chance (1 in x). Range: (1-1,048,567)
echo Leave blank for 1 in 4096.
set /p chance = Input:
set /a chance = %chance%+0
if %chance% GEQ 1 (
if %chance% LEQ 1048567 (
goto setDelay
)
)
echo Invalid Input.
pause
goto setChance
:setDelay
cls
echo Set delay between attempts in seconds. Range: (1-60).
echo Leave blank for no delay.
set /p delay = Input:
set /a delay = %delay%+0
if %delay% == nul (
goto loopStart
)
if %delay% GEQ 1 (
if %delay% LEQ 60 (
cls
goto loopStart
)
)
echo Invalid Input.
pause
goto settings
:loopStart
set /a count = %count%+1
set /a rand = %random% %% %chance%+1
if %rand% == 1 (
echo Attempt: %count% | Shiny: Yes!
pause
)
else (
echo Attempt: %count% | Shiny: No
)
goto loopStart
I suggest to read first debugging a batch file and second the answer onWhy is no string output with 'echo %var%' after using 'set var = text' on command line?
Next look on your rewritten code below:
:setup
#echo off
title Pokemon Shiny Sim
set "delay=0"
set "count=0"
set "chance=4096"
:settings
:setChance
cls
echo Set shiny chance (1 in x). Range: (1-1,048,567)
echo Leave blank for 1 in 4096.
set /P "chance=Input: "
set /A chance+=0
if %chance% GEQ 1 if %chance% LEQ 1048567 goto setDelay
echo Invalid input.
pause
goto setChance
:setDelay
cls
echo Set delay between attempts in seconds. Range: (1-60).
echo Leave blank for no delay.
set /P "delay=Input: "
set /A delay+=0
if %delay% == 0 goto loopStart
if %delay% GEQ 1 if %delay% LEQ 60 cls & goto loopStart
echo Invalid input.
pause
goto settings
:loopStart
set /A count+=1
set /A rand=%random% %% chance + 1
if %rand% == 1 (
echo Attempt: %count% ^| Shiny: Yes!
pause
) else (
echo Attempt: %count% ^| Shiny: No
)
goto loopStart
All spaces around the equal signs are removed in this batch code.
The command line set "delay = nul" is modified to set "delay=0" because the condition if %delay% == nul is never true after execution of set /a delay = %delay%+0 resulting in execution of set /a delay = nul + 0 which results in assigning value 0 to environment variable delay on nul not existing as environment variable with that name having an integer value. The result of a valid arithmetic expression is always a number assigned as string to the environment variable and never a string like nul.
set /a chance = %chance%+0 is modified to set /A chance+=0 and set /a delay = %delay%+0 is modified to set /A delay+=0 because otherwise the input check is insecure as the user has for example the freedom to enter | for variable chance resulting in execution of command line set /a chance = |+0 which cause an unexpected exit of batch file execution.
Never use %variable% or !variable! in an arithmetic expression as not needed in general.
The help output on several pages on running set /? in a command prompt window explains in chapter about usage of set /A that each string which can't be interpreted as number or operator is interpreted automatically as name of an environment variable whose current value should be converted to an integer on evaluation of the expression. If the environment variable is not defined at all or its value can't be successfully converted to a 32-bit signed integer, it is replaced in the expression by integer value 0.
There are exceptions like the usage of a random number in an arithmetic expression which requires %random% or !random! or when a variable name contains a space character or a character which would be interpreted as operator. In such cases it is necessary that the Windows command interpreter replaces the environment variable name already in preprocessing state or immediately before execution of the command set by random value respectively value of the environment variable.
set /a chance = %chance%+0 makes it also possible that the user of this batch file enters for example PROCESSOR_LEVEL or PROCESSOR_REVISION and this input although not being a number at all would be handled as valid because those two strings are the names of environment variables having numbers as values. PROCESSOR_REVISION has by default a hexadecimal number assigned which can be processed nevertheless completely or partly as number by command set.
Another syntax error is in block
if %rand% == 1 (
echo Attempt: %count% | Shiny: Yes!
pause
)
else (
echo Attempt: %count% | Shiny: No
)
The keyword else must be on same line as the closing ) of true branch of the IF condition separated from ) with a space character.
And redirection operator | must be escaped with caret character ^ to be interpreted as literal character to output into console window.
Note: set /A chance+=0 makes it still possible to enter for example 170 percent or 170X which results in chance having value 170 and therefore input is valid although in real the entered string is not a number.
For understanding the used commands and how they work, open a command prompt window, execute there the following commands, and read entirely all help pages displayed for each command very carefully.
cls /?
echo /?
goto /?
if /?
pause /?
set /?
title /?
I haven't tested the code yet, but I found some fatal issues in the code.
Mis-setting variable
set /a count = %count% + 1
This sets a variable count (Note the space!). Remove the space! Also, this can be shortened to set /a count+=1.
ECHOing special characters
| is one of the special characters reserved for redirection in batch. To properly echo it, use echo string ^| string instead.
Poor IF statement practice
if %rand% == 1 (
only works when %rand% is alphanumeric. If %rand% is space, the cmd.exe sees:
if == 1 (
which is incorrect.
To correct it, do
if "%rand%"=="1" (
Alternatively, use EQU for numeric comparison, and == for string comparison.
How come when I do this in my game it works
set /a Monster=%random% * 2 / 32768 + 1
But this one doesn't
(Note: MHP = 10 and DamageDealt = 5)
set /a MHP=%MHP% - %DamageDealt%
And when I run the second one it says "Missing Operator".
But it only says it once if I run the thing twice...
Here's a bigger snippit:
:FightExplora
if %HP%=<0 goto GAMEOVERExplora
if %MHP%=<0 goto FightEndExplora
cls
echo HP: %HP%/%MaxHP% Str: %Strength% XP:%XP%/%LVUP% LV: %LV%
$%Money%
echo.
echo You encountered a %Monster%!
echo Monster -- HP: %MHP%/%MaxMHP% Str: %MonsterSTR%
echo.
echo [1-Attack] [2-Heal]
set /p Action="What will you do? > "
echo.
if %Action%==1 (
set /a DamageDealt=%random% * %Strength% / 32768 + 1
set /a MHP=%MHP% - %DamageDealt%
echo You did %DamageDealt% to the %Monster%
goto EnemyTurnExplora
)
if %Action%==2 (
set /a HealAMT=%random% * %MaxHP% / 32768 + (%MaxHP% / %Strength%)
set HP=%HealAMT%
if %HP% => %MaxHP% set %HP%=%MaxHP%
echo You healed %HealAMT% HP
goto EnemyTurnExplora
)
:EnemyTurnExplora
echo.
pause >nul
::Enemy Damage
echo.
set /a DamageTaken=%random% * %MonsterSTR% / 32768 + 1
set /a HP=%HP% - %DamageTaken%
echo The %Monster% dealt %DamageTaken% to you.
echo.
pause >nul
goto FightExplora
Also, when you say to heal, then the command window closes and I don't know why...
Do not expand environment variables within an arithmetic expression using %Variable% syntax as this does not work within command blocks when the referenced environment variable is defined or modified within same command block. Also delayed expansion with reference syntax !Variable! is not needed within an arithmetic expression.
Run in a command prompt window set /? and read carefully the output help explaining arithmetic expressions as well as delayed expansion. As you can read on studying the help you can simply use:
set /A MHP-=DamageDealt
Any non-numeric strings in the expression are treated as environment variable names whose values are converted to numbers before using them. If an environment variable name is specified but is not defined in the current environment, then a value of zero is used. This allows you to do arithmetic with environment variable values without having to type all those % signs to get their values.
The reason for the error on using:
set /a MHP=%MHP% - %DamageDealt%
Either environment variable MHP or DamageDealt or both were not defined on expanding the environment variables and the result was the execution of one of those 3 command lines:
set /a MHP= - 50
set /a MHP= 200 -
set /a MHP= -
This can't happen with using:
set /A MHP=MHP - DamageDealt
set /A MHP-=DamageDealt
Each environment variable name on right side of the equal sign is replaced with 0 if the referenced environment variable does not exist at all on evaluation of the expression.
I am trying to use nested if-else statements in order to implement or operator.
The problem is that the code only works outside the last nested else statement and I can't figure out why.
I added some notes marked with // that are not actually in the script to help you get a clue of what I am trying to do.
Here is my batch script:
:computerMakePick
setLocal
set /a currentNumber= 15
set /a addOne=%currentNumber%+1
set /a addTwo=%currentNumber%+2
//the next segment implements OR operator for two conditions using nested if-else statement
if %addOne% == 7 ( //checking first condition.
echo Computer chose: %addOne%
set /a currentNumber= %addOne%
)else (
if %addTwo% == 8 ( // now checking: OR second condition
echo Computer chose: %addTwo%
set /a currentNumber= %addTwo%
)else ( // if not both of the above then do this. NOW this section below doesn't work
set /a bottomlimit= 1
set /a upperlimit= 2
set /a limit=%upperlimit%-%bottomlimit%+1
set /a randomChoice= %bottomlimit% + %RANDOM% %% %limit%
set /a currentNumber= %currentNumber%+%randomChoice%
echo Computer chose: %currentNumber%
)
)
endLocal & set /a currentNumber= %currentNumber%
goto :eof
If I take the last else section to outside like this below, then it works:
:computerMakePick
setLocal
set /a currentNumber= 15
set /a addOne=%currentNumber%+1
set /a addTwo=%currentNumber%+2
//the next segment implements OR operator for two conditions using nested if-else statement
if %addOne% == 7 ( //checking first condition.
echo Computer chose: %addOne%
set /a currentNumber= %addOne%
)else (
if %addTwo% == 8 ( // now checking: OR second condition
echo Computer chose: %addTwo%
set /a currentNumber= %addTwo%
)else (
echo. // need to put something in here or else it doesn't work.
) // could also delete this last else-statment but it doesn't matter
)
//now this below works fine. and I don't understand why under second-else section it doesn't
set /a bottomlimit= 1
set /a upperlimit= 2
set /a limit=%upperlimit%-%bottomlimit%+1
set /a randomChoice= %bottomlimit% + %RANDOM% %% %limit%
set /a currentNumber= %currentNumber%+%randomChoice%
echo Computer chose: %currentNumber%
endLocal & set /a currentNumber= %currentNumber%
goto :eof
By saying it's not working I mean if I print the values of each variable: bottomlimit, upperlimit, limit, etc. when they are defined inside the second else statement, for example for the command line echo value of limit is = %limit% I get blanks (nothing).
Why is this happening and how can I fix it to work inside the second else statement?
Use the following code:
#echo off
:computerMakePick
setLocal
set "currentNumber=15"
set /a addOne=currentNumber + 1
set /a addTwo=currentNumber + 2
rem // the next segment implements OR operator for two conditions using nested if-else statement
if %addOne% == 7 ( rem // checking first condition.
echo Computer chose: %addOne%
set "currentNumber=%addOne%"
) else if %addTwo% == 8 ( rem // now checking: OR second condition
echo Computer chose: %addTwo%
set "currentNumber=%addTwo%"
) else ( rem // if not both of the above then do this. NOW this section below doesn't work
set "bottomlimit=1"
set "upperlimit=2"
set /a limit=upperlimit - bottomlimit + 1
set /a randomChoice=bottomlimit + %RANDOM% %% limit
set /a currentNumber+=randomChoice
setlocal EnableDelayedExpansion
echo Computer chose: !currentNumber!
endlocal
)
endLocal & set "currentNumber=%currentNumber%"
goto :EOF
Environment variables are always of type string. So even on using integers, the numbers are stored in memory as strings and not as integers. Therefore don't use set /a variable=number if there is no real reason to do so as this results in converting number from string to integer for the arithmetic expression, and converting it back from integer to string for assigning the result of this arithmetic expression to environment variable.
Usage of environment variable expansion within an arithmetic expression which is the string after set /a is usually nonsense as Windows command interpreter automatically interprets each string not being a number or an operator as name of an environment variable whose current value has to be converted to an integer for evaluation of the expression.
Yes, whether immediate nor delayed expansion is needed within an arithmetic expression even when the set /a command line is within a command block.
And in batch files // is not a comment, use command REM and take into account that Windows command interpreter first parses the lines with command REM and then executes the command if there is no syntax error, see %~ in REM statement.
For more details:
Run in a command prompt window set /? and really read carefully everything of output help.
If you use any of the logical or modulus operators, you will need to
enclose the expression string in quotes. Any non-numeric strings in the
expression are treated as environment variable names whose values are
converted to numbers before using them. If an environment variable name
is specified but is not defined in the current environment, then a value
of zero is used. This allows you to do arithmetic with environment
variable values without having to type all those % signs to get their
values.
Read the answer Why is no string output with 'echo %var%' after using 'set var = text' on command line?
Read the answer on IF ELSE syntax error within batch file?
Variables within the else-statement are not expanded. Use setlocal enabledelayedexpansion instead and denote your variables with exclamation marks:
:computerMakePick
setLocal enabledelayedexpansion
set /a currentNumber= 15
set /a addOne=%currentNumber%+1
set /a addTwo=%currentNumber%+2
if %addOne% == 7 (
echo Computer chose: %addOne%
set /a currentNumber= %addOne%
)else (
if %addTwo% == 8 (
echo Computer chose: %addTwo%
set /a currentNumber= %addTwo%
)else (
set /a bottomlimit= 1
set /a upperlimit= 2
set /a limit=!upperlimit!-!bottomlimit!+1
set /a randomChoice= !bottomlimit! + !RANDOM! %% !limit!
set /a currentNumber= !currentNumber!+!randomChoice!
echo Computer chose: !currentNumber!
)
)
endLocal & set /a currentNumber= %currentNumber%
goto :eof
Error Code:
If was unexpected at this time
The code sets the stats for each player then it calls the function to determine the amount of damage based on the stats and other variables
What I want to do is call a function with two IF statements within it
Example:
#echo off
set /a level=5
set /a opponentLevel=5
set /a movePower=50
set moveType=physical
goto player
:damageCalculator
if %moveType%==physical (
pause
set /a damage=(((( 2 * %level% / 5 + 2) * %attackStat% * %movePower% / %opponentDefenceStat%) / 50) + 2)
set /a opponentHealth-=%damage%
) else if %moveType%==special (
set /a damage=(((( 2 * %level% / 5 + 2) * %spAttackStat% * %movePower% / %opponentSpDefenceStat%) / 50) + 2)
set /a opponentHealth-=%damage%
)
goto :eof
:player
set type=fire
set/a health=19
set/a attackStat=10
set/a defenceStat=10
set/a spAttackStat=11
set/a spDefenceStat=10
set/a speedStat=12
:opponent
set /a opponentHealth=18
set /a opponentAttackStat=10
set /a opponentDefenceStat=9
set /a opponentSpAttackStat=8
set /a opponentSpDefenceStat=9
set /a opponentSpeedStat=13
:attack
pause
cls
call :damageCalculator
echo It did %damage% Damage!!
pause>nul
Is this just one of those things that batch can't do?
update per edited question
Your script has a few small issues. Firstly, I'll point out that it's often helpful to rem out #echo off when trying to track down the cause of a problem. Doing so in this case shows that the line causing your error is your first set /a line.
The reason your if statements are failing is because the parentheses within your math are being treated as the end of your code block. As soon as the closing parenthesis of ...5 + 2) is encountered, the batch interpreter treats that as the end of your if statement, and therefore gets confused when there's more stuff on the line. You need to quote your set /a statements to prevent this.
set /a "damage=(((( 2 * level / 5 + 2) * attackStat * movePower / opponentDefenceStat) / 50) + 2)"
See how I did set /a "variable=value" there? You could also escape the closing parentheses with a caret -- e.g. ^), but quoting the "var=value" is a little easier to read I think. The quotation marks keep the contents within the context of the command. They're basically saying, "This is a single token. It's a distinct part of the set command, not the code block as a whole." As a bonus, you can also see that the % signs aren't needed to retrieve variable values within a set /a command. Neat, huh?
You've got another problem. Since you're setting the %damage% variable within the same parenthetical code block as you're retrieving it, %damage% is going to be evaluated too early. You could setlocal enabledelayedexpansion and retrieve it as !damage!, and that would certainly work. But there's a simpler fix. Just put it outside the if statements. You're doing set /a opponentHealth-=damage regardless of whether the move type is physical or special, anyway, right?
:damageCalculator
if "%moveType%"=="physical" (
set /a "damage=(((( 2 * level / 5 + 2) * attackStat * movePower / opponentDefenceStat) / 50) + 2)"
) else if "%moveType%"=="special" (
set /a "damage=(((( 2 * level / 5 + 2) * spAttackStat * movePower / opponentSpDefenceStat) / 50) + 2)"
)
set /a opponentHealth-=damage
goto :eof
But still, you should include setlocal just below #echo off to keep from junking up your environment with variables that have no meaning outside the scope of this script.
Here's another tip. You can combine many statements within a single set /a line.
Before:
set /a level=5
set /a opponentLevel=5
set /a movePower=50
set "moveType=physical"
After:
set /a level=5, opponentLevel=5, movePower=50
set "moveType=physical"
original answer
Change your second if to else if or add a carriage return before it (after the preceding parenthesis). Also, move your goto :EOF to the next line after the closing parenthesis.
The explanation for this is that the cmd interpreter treats a parenthetical code block as a single command. So in essense,
if [true condition] (
action
) second command
is being evaluated as
if [true condition] (action) second command
which results in an error because there's no line break or other separator between the first command (the if) and the second. Here's an example of a valid compound command:
#echo off & setlocal
Compound command need:
unconditional AND (& -- right side always executes after the left)
example: endlocal & goto :EOF
logical AND (&& -- right side executes only if the preceding command exited zero)
example: find /i "text" "textfile.txt" >NUL && echo Text was found
pipe (| -- makes the command on the right do something with the output generated by the command on the left)
example: dir /s /b | more
logical OR (|| -- right side executes only if the preceding command exited non-zero)
example: tasklist | find /i "iexplore.exe" >NUL || echo Internet Explorer not running
... or in the case of an if statement, else.
if condition 1 (
action 1
) else if condition 2 (
action 2
) else (
action 3
)
Or if you want to check that two conditions are true:
if %var% leq 10 if %var% geq 5 (
echo Variable is between 5 and 10.
)
Of course, you don't have to use compound statements. There's no reason why a function can't have multiple if statements that aren't compound.
:fn <str>
if "%~1"=="fish" (echo Bloop.)
if "%~1"=="cats" (echo Meow.)
if "%~1"=="dogs" (echo Grrrr.)
goto :EOF
... is perfectly valid.
I need to do a floating-point division in a dos batch.
I didn't find a way to do it. Something like this :
SET /A Res=10/3
returns a integer number.
Is it possible to do it ?
I know this is a very old topic, but I can't found a simple Batch method in all previous answers, so I post here a pure Batch solution that is very simple to use.
Perform operations using fixed point arithmetic in Batch is simple. "Fixed point" means that you must set a number of decimals in advance and keep it throughout the operations. Add and subtract operations between two Fixed Point numbers are performed directly. Multiply and division operations requires an auxiliary variable, that we can call "one", with the value of 1 with the right number of decimals (as "0" digits). After multiply, divide the product by "one"; before division, multiply the dividend by "one". Here it is:
#echo off
setlocal EnableDelayedExpansion
set decimals=2
set /A one=1, decimalsP1=decimals+1
for /L %%i in (1,1,%decimals%) do set "one=!one!0"
:getNumber
set /P "numA=Enter a number with %decimals% decimals: "
if "!numA:~-%decimalsP1%,1!" equ "." goto numOK
echo The number must have a point and %decimals% decimals
goto getNumber
:numOK
set numB=2.54
set "fpA=%numA:.=%"
set "fpB=%numB:.=%"
set /A add=fpA+fpB, sub=fpA-fpB, mul=fpA*fpB/one, div=fpA*one/fpB
echo %numA% + %numB% = !add:~0,-%decimals%!.!add:~-%decimals%!
echo %numA% - %numB% = !sub:~0,-%decimals%!.!sub:~-%decimals%!
echo %numA% * %numB% = !mul:~0,-%decimals%!.!mul:~-%decimals%!
echo %numA% / %numB% = !div:~0,-%decimals%!.!div:~-%decimals%!
For example:
Enter a number with 2 decimals: 3.76
3.76 + 2.54 = 6.30
3.76 - 2.54 = 1.22
3.76 * 2.54 = 9.55
3.76 / 2.54 = 1.48
Batch files as such do not support the floating point arithmetic. However, this article suggests a workaround that uses an external script file to do calculations. The script file should use some sort of eval function to evaluate the expression passed as an argument and return the result. Here's a sample VBScript file (eval.vbs) that does this:
WScript.Echo Eval(WScript.Arguments(0))
You can call this external script from your batch file, specify the expression to be evaluated and get the result back. For example:
#echo off
for /f %%n in ('cscript //nologo eval.vbs "10/3"') do (
set res=%%n
)
echo %res%
Of course, you'll get the result as a string, but it's better than nothing anyway, and you can pass the obtained result to the eval script as part of another expression.
According to this reference, there is no floating point type in DOS batch language:
Although variables do exist in the DOS batch programming language, they are extremely limited. There are no integer, pointer or floating point variable types, only strings.
I think what you are trying to do will be impossible without implementing your own division scheme to calculate the remainder explicitly.
I recently came across this batch file to compute an approximation of Pi.
There is a DivideByInteger label that might be useful to you: Stupid-Coding-Tricks-A-Batch-of-Pi
It uses a set of MaxQuadIndex variables, each containing a four-digit number (quadruple), in order to store the entire result. The code allows division by an integer between 1 and 10000, inclusive.
:DivideByInteger
if defined PiDebug echo.DivideByInteger %1 %2
set /a DBI_Carry = 0
for /L %%i in (!MaxQuadIndex!, -1, 0) do (
set /a DBI_Digit = DBI_Carry*10000 + %1_%%i
set /a DBI_Carry = DBI_Digit %% %2
set /a %1_%%i = DBI_Digit / %2
)
goto :EOF
A Print label is also available…
try this
SETLOCAL EnableExtensions EnableDelayedExpansion
call :calc_ 1 (99-(100*5/100^)^)
echo !calc_v!
goto :EOF
:calc_
set scale_=1
set calc_v=
for /l %%i in (1,1,%1) do set /a scale_*=10
set /a "calc_v=!scale_!*%2"
set /a calc_v1=!calc_v!/!scale_!
set /a calc_v2=!calc_v!-!calc_v1!*!scale_!
set calc_v=!calc_v1!.!calc_v2!
goto :EOF
just change
call :calc_ decimalpoint equataion
in the example
decimalpoint is 1
equataion is (99-(100*5/100^)^) ;make sure if you use () that you insert ^ before ) as in ^)
the answer is 94.0
if decimalpoint is 2
and equataion is 22/7 ;π pi
the answer is 3.14
I wrote a pure batch file specifically to do division. It takes the first number you input, and then divides it by the second one, and displays the result with as many decimal points as you specify.
Echo off
cls
if NOT "%3" == "" (
set n1=%1
set n2=%2
set max=%3
goto :begin
)
set counter=2
set n1=1
set n2=1
set ans=
:start
Echo.
Echo. 1 / 2
Echo.
Set /p N1= 1?
set /p N2= 2?
Set /p Max= Out how many Decimal Points?
:begin
set /a TmpAns=%N1%/%N2%
set ans=%TmpAns%.
:: Echo.%ans%.>Answer.txt
<nul set /p "=%Tmpans%."
set /a TmpSub=%N2%*%TmpAns%
set /a N1=%N1%-%TmpSub%
set N1=%N1%0
If NOT "%n1%" == "00" (
if %n1% LSS %N2% (
set N1=%N1%0
set ans=%ans%0
)
) else (
Goto :Finished
)
set count=0
:loop
If "%count%" == "%max%" (
Goto :Finished
)
set /a TmpAns=%N1%/%N2%
set ans=%ans%%TmpAns%
<nul set /p "=%Tmpans%"
set /a TmpSub=%N2%*%TmpAns%
set /a N1=%N1%-%TmpSub%
set N1=%N1%0
If NOT "%n1%" == "00" (
if %n1% LSS %N2% (
set N1=%N1%0
set ans=%ans%0
)
) else (
Goto :Finished
)
set /a count=%count%+1
goto :loop
:finished
cls
Echo.
Echo.
Echo.The Number
Echo.%ans%
Echo.
Echo.
set n1=1
set n2=1
pause
goto :eof
:eof
The answer put into the variable %Ans%. It can also be called with parameters. ("Divide.bat 50 27 5" would give you 50/27 out 5 decimal points.)
Since nowadays PowerShell is present on almost all machines, I would let PowerShell do the math and return the result to the batch.
Example:
set divident=10
set divisor=3
for /f "delims=" %%a in ('powershell -Command %divident%/%divisor%') do set result=%%a
#echo %result%
Explanation:
Input variables: Use set variables to define divident and divisor.
Calling powershell and assign result to a batch variable: for /f "delims=" %%a in ('powershell -Command ...) do set result=%%a (you may also check here: How to put a single PowerShell output string into a cmd variable?)
Note the above code will only work with integer input variables.
To support floating point input variables, we need to send the variables as strings inside quotations ("%variable%") and convert the strings within PowerShell back to Double, otherwise batch would interpret the commas as delimiters and PowerShell could not interpret the numbers.
Example:
set divident=10,5
set divisor=3,4
for /f "delims=" %%a in ('powershell -Command [convert]::ToDouble^(\"%divident%\"^)
/[convert]::ToDouble^(\"%divisor%\"^)') do set result=%%a
#echo %result%
Explanation:
Note in PowerShell you would do this like [convert]::ToDouble("10,5")/[convert]::ToDouble("3,5"). However in batch we need to escape the quotes using backslash, and we also need to add a "^" sign before and after the quoted parts: [convert]::ToDouble^("%divident%"^)/[convert]::ToDouble^("%divisor%"^)
If you're running in a command shell on Windows (rather than DOS), you can use VBScript to evaluate complex expressions including floating point math for you.
I have written a small helper library you can call to do this.
EvalBat Library on GitHub