2015-09-24 144 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