2015-09-24 55 views
0
@echo off 
if "%1"=="" (
:WriteAgain 
set x= 
set /p variables=Write your expression 
if "%variables%"=="help" (
echo Use arithmetical operations and numbers without spaces. + for sum, * for multiplication,/for 

devision, - for subtraction 
exit 
) else (
set variables=%variables: =% 
set /a x=%Variables% 2>Error.txt 
if %errorlevel% neq 0 goto ErrorOccured 
echo %x% 
pause 
exit 
) 
:ErrorOccured 
echo Your expression is not valid 
goto WriteAgain 
) else (
set variables=%* 
set variables=%variables: =% 
set /a x=%variables% 2>Error.txt 
if %errorlevel% neq 0 goto ErrorOccured 
echo %x% 
) 

問候,這是一個簡單的計算。它可以直接從CMD中使用,但第一if不工作,也無法通過如果在.bat文件中

) else (
set variables=%variables: =% 
set /a x=%Variables% 2>Error.txt 
if %errorlevel% neq 0 goto ErrorOccured 
echo %x% 

總是ErrorOccured。我沒有看到任何問題,它沒有第一個工作if

+1

'批處理中不支持if-else-else'。另外跳入內部或進入''(''block')'也是一個壞主意。每個'goto'都會打破塊的上下文。重新思考你的邏輯(程序流程)。 – Stephan

+1

另外,標籤在()內不受支持。第一個回聲格式錯誤 – Paul

回答

0

我不知道它是否符合您的期望,我無法運行ErrorOccured標籤。

@echo off 
cls 
set x= 

:WriteAgain 
if "%1"=="" (
    set /p "variables=Write your expression " || cls &goto help 
    ) else (
    set "variables=%*" 
) 

set variables=%variables: =% 
set /a x=%variables% 2>Error.txt 
:: if %errorlevel% neq 0 goto ErrorOccured 
if not ERRORLEVEL 0 goto ErrorOccured 
call :result %variables% %x% 
exit /b 0 

:help 
echo(
echo Use arithmetical operations and numbers without spaces. 
echo + for sum, * for multiplication,/for devision, - for subtraction 
goto WriteAgain 

:result 
echo formula is %~1 and the result is %~2 
goto:EOF 

:ErrorOccured 
cls 
echo(
echo Your expression is not valid 
goto :help 

exit /b 0 

這當然必須進行優化。

+0

'如果NOT errorlevel 0'與'if errorlevel%LSS 0'相同,因爲'如果errorlevel 0'語句應該被讀爲_if errorlevel is_ **大於或等於** _zero_。 – JosefZ

1

也許下一個代碼可以幫助。注意EnableDelayedExpansion和適當的引用以允許在set /?中看到的所有算術運算。

@ECHO OFF 
SETLOCAL EnableExtensions EnableDelayedExpansion 
if "%~1"=="" goto NeedHelp 
set "variables=%*" 

:CommonCalc 
if "%variables%"=="" goto ErrorOccured 
rem spaces do not matter set "variables=!variables: =!" 
set /a "x=!variables!" 2>Error.txt 
if %errorlevel% neq 0 goto ErrorOccured 
echo !variables!=%x% 
exit /B 

:WriteAgain 
set "x=" 
set "variables=" 
set /p "variables=Write your expression: " 
if /I "!variables!"=="" goto NeedHelp 
goto CommonCalc 

:NeedHelp 
echo Use arithmetical operations and numbers without spaces. 
echo + for sum, * for multiplication,/for division, - for subtraction 
echo %% for modulus ^(remainder after division^) 
goto WriteAgain 

:ErrorOccured 
echo Your "!variables!" expression is not valid ^(%errorlevel%^) 
rem next line: clear errorlevel to 0 
(call) 
goto NeedHelp 

然而,如果用作批量行參數proper escaping一些運營商是要緊。例如:

  • 否定32766441.bat ^^^!0返回!0=1
  • 邏輯32766441.bat 6^|9返回6|9=15
  • shift32766441.bat 5^<^<3返回5<<3=40

(call)特技憑藉清除errorlevelthis dbenham's answer

+0

如果我是OP,我會選擇你的答案。 +1 – Paul