批处理-函数定义及应用01

 1 @echo off
 2 :: 批处理中所谓的函数,是用标签定义功能充当的。支持参数的传递,类似脚本文件运行时命令行参数的传递。
 3 ::  函数返回值用标签作为变量名作为返回使用,用完标签名变量立即释放变量,避免后面同样需要调用该函数,引起返回值的混乱。
 4 :: exit /b code  在标签定义中表示退出当前函数,并返回错误状态值code。在call调用完毕后,回到call调用处继续执行后续指令。
 5 ::               不带/b表示直接退出cmd环境。
 6 
 7 
 8 
 9 :::::::::::::::::::::::::::::::Main Begin::::::::::::::::::::::::::::::::::::::::::::::
10 :Main
11 echo;欢迎进入批处理天地!
12 echo;
13 echo;加法运算开始.
14 set /p n1=请输入第一个数字:
15 set /p n2=请输入第二个数字:
16 
17 call :IsDigital %n1% 
18 set r1=%errorlevel% 
19 call :IsDigital %n2% 
20 set r2=%errorlevel%
21 
22 
23 if "%r1%"=="200" (
24   if "%r2%"=="200" (     
25       call :Add %n1% %n2%
26       call,echo;%n1%与%n2%之和为:%%Add%%
27    ) else (echo;%n2%不是数字无法参与运算.)
28 ) else (echo;%n1%不是数字无法参与计算.)
29 
30 pause & exit 
31 :::::::::::::::::::::::::::::::Main End::::::::::::::::::::::::::::::::::::::::::::::
32 
33 
34 :::::::::::::::::::::::::::::::Add Begin::::::::::::::::::::::::::::::::::::::::::
35 ::   功能:两数相加。
36 :Add
37 ::变量传递查看。
38 ::echo;%*
39 set /a num1=%1
40 set /a num2=%2
41 set sum=
42 set /a sum=%num1% + %num2%
43 ::echo;%num1% + %num2% = %sum%
44 ::返回值用标签当作变量返回。
45 set /a add=%sum% &exit /b 0
46 :::::::::::::::::::::::::::::::Add End::::::::::::::::::::::::::::::::::::::::::
47 
48 :::::::::::::::::::::::::::::IsDigital Begin:::::::::::::::::::::::::::::::::::::::::::
49 ::    功能:判断给入的字符是否是纯数字。
50 ::        exitcode  200 表示成功,是数字。250 表示失败,不是数字。
51 :IsDigital
52 set "num=%1"
53 ::情况一:数字字符串中含空格。
54 ::set num=%num: =%
55 echo;%num%|findstr "^[0-9][0-9]*$" >nul && call,set IsDigital=%%num%%
56 if not defined IsDigital (echo;%num%不是数字. & exit /b 250) else (echo;%num%是纯数字. & exit /b 200)
57 :::::::::::::::::::::::::::::IsDigital End:::::::::::::::::::::::::::::::::::::::::::

 

posted @ 2020-03-29 22:17  寻不断  阅读(907)  评论(0编辑  收藏  举报