How to For-Loop and do Math/Arithmetic Operations in Windows/NT

  • 时间:2020-09-25 11:32:47
  • 分类:网络文摘
  • 阅读:147 次

The FizzBuzz is a good example to start learning a programming language – which contains the exercise of using a loop (either for-loop or a while-loop), Arithmetic operations (modulus), using a if-else condition, and finally printing to the console. You might want to exercise defining a function (containing the logics) and call/invoke it.

In Windows/NT batch command (file extension *.bat or *.cmd i.e. *.cmd indicates that the script is not for intended use on 16-bit DOS or older OS – and the *.bat indicates that the batch script can be run on all platforms), it is a bit tricky to do the Arithmetic operations. The following Batch program shows how we can do a for loop, testing if a variable is multiples of 3 or 5, and print something to the console.

@ECHO OFF
SETLOCAL ENABLEEXTENSIONS
SETLOCAL ENABLEDELAYEDEXPANSION

for /L %%i in (1,1,100) do (
    set /a mod3=%%i %% 3
    set /a mod5=%%i %% 5
    @REM mod3and5==0 if mod3 and mod5
    set /a mod3and5=!mod3! + !mod5!
    if "!mod3and5!"=="0" (
        echo FizzBuzz
    ) else (
        if "!mod3!"=="0" (
            echo Fizz
        ) else (
            if "!mod5!"=="0" (
                echo Buzz
            ) else (
                echo %%i
            )
        )
    )
)

ENDLOCAL
ENDLOCAL

SETLOCAL ENABLEDELAYEDEXPANSION allows windows/NT batch to use variables – which are noted as !variable!. The for /L %%variable(start, stop, step) is a simple for-loop that will increment the variable from start to stop with a step.

The set /a performs some Arithmetic operations where we use %% for integer modules. and finally the if something==something ( do-one-thing ) else ( do-another-thing) performs the if-else check.

Please be noted that there is no Logical AND or OR, thus it will be a bit tricky to emulate this in windows batch. You can always have nested-if checks for AND operator.

if !A!=1 (
   if !B!=2 (
     echo A=1 and B=2
   )
)
Batch-File-Commands How to For-Loop and do Math/Arithmetic Operations in Windows/NT Batch - the FizzBuzz Programming Example bash script batch script math programming languages windows batch

Batch File Commands

–EOF (The Ultimate Computing & Technology Blog) —

推荐阅读:
KBS1在线直播「高清」  windows10提示“我们无法在此设备上激活windows”_windows10激活失败提示解决方法  韩国kbs2直播-韩国kbs2电视台直播「高清」  如何在墙内向Blogger独立博客上发布文章  利用Cloudflare Worker反代Blogger博客实现国内正常访问  国外免费空间1G免费php空间大流量,大家可以玩玩  韩国KBS24直播「高清」  edge浏览器怎么查看和管理扩展程序权限_edge浏览器扩展程序权限管理方法  kbs world 直播「高清」  广东体育在线直播-广东电视台体育频道直播「高清」 
评论列表
添加评论