calculating the average of 10 for loop results in

2019-09-14 16:32发布

so i've created a for loop that calculates (x mod 6) + 2 for every number from 1-10 (inclusive), with "x" representing each individual number as the loop increments. however, i'd like to calculate the average for each of the 10 results, but i actually have no idea as to how i'd format the loop to do so. i'd rather not do something like echo "1 + 2 + 3 + etc" as that seems extremely lazy and ill-constructed. i feel like this is something relatively easy, but i've tried searching it up and attempting another loop, but to no avail. any and all help is much appreciated!

here's the loop:

:ForLoop
@echo off &setlocal enabledelayedexpansion

echo This loop calculates the results for (x mod 6) + 2 with x being each number from1-10 (inclusive).
echo.
for /L %%x in (1, 1, 10) do (
    SET /a VAR=%%x %% 6+2
    set /a CAL=!VAR! %% 8
    echo %%x MOD 6 + 2 = !CAL!
)

1条回答
孤傲高冷的网名
2楼-- · 2019-09-14 17:00
@ECHO OFF
SETLOCAL ENABLEDELAYEDEXPANSION 
:ForLoop

echo This loop calculates the results for (x mod 6) + 2 with x being each number from1-10 (inclusive).
echo.
SET /a iterations=10
SET /a sum=0
for /L %%x in (1, 1, %iterations%) do (
    SET /a VAR=%%x %% 6+2
    SET /a sum+=var
    SET /a avg=sum / %%x
    echo %%x MOD 6 + 2 = !var! average so far=!avg! (from !sum! / %%x^)
)

GOTO :EOF

There's no need to do the %% 8 jazz - since var can only be (0..5)+2, this gives a range of 2..7.

set /a uses the run-time value of the variables, so !var! is not required - %var% would use the initial value of var.

Note that the average is truncated as batch does integer mathematics.

查看更多
登录 后发表回答