Discussion forum for all Windows batch related topics.
Moderator: DosItHelp
-
shant93
- Posts: 2
- Joined: 14 Nov 2009 09:55
#1
Post
by shant93 » 14 Nov 2009 10:01
I am new at batch file programming (very new), and I tried to make a batch file that would give the factorial of a number between 1 and 10
After fixing any issues with the first line of text, I tried it again and it looped the message "The syntax is incorrect".
For those who don't know, the factorial of a number "x" is 1*2*3*4*...*x
E.g. 4 factorial is 1*2*3*4=24
here is the code, I know there probably are hundreds of mistakes.
Code: Select all
@echo off
if ("%1" GTR "10") (goto :bad) else (goto :good)
:bad
echo The number is too big
:good
set %n%=1
goto :math
:math
set %m%=%n%+1
if /i not (%m% GTR %1) (goto :matha) else (goto :end)
:matha
set %r%=%b%*%m%
set %b%=%r%
set %n%=%m%
goto :math
:end
echo %1 factorial is %r.
pause
@echo on
cls
-
shant93
- Posts: 2
- Joined: 14 Nov 2009 09:55
#2
Post
by shant93 » 14 Nov 2009 17:34
Ok, I fixed a few mistakes, but now it outputs %_result% as nothing. Also, the first IF line that checks whether the number is greater than 10 doesn't work
Code: Select all
@echo off
if "%1" GTR 10 (goto :bad) else (goto :good)
:bad
echo The number is too big
goto :rend
:good
set /A _number=1
set /A _preres=1
goto :math
:math
set /A _number+=1
if ("_number" LEQ "%1") (goto :matha) else (goto :end)
:matha
set
set /A _result=_number*_preres
set /A _preres=_result
goto :math
:end
echo %1 factorial is %_result%.
goto :rend
:rend
pause
@echo on
cls
________________
EDIT:
Nevermind, I made everything easier with a FOR loop and fixed the problem:
Code: Select all
@echo off
set /a _res=1
FOR /l %%n IN (1,1,%1) DO set /A _res*=%%n
echo %_res%
@echo on