2017-04-02 91 views
0

所以我创建了一个for循环,用于计算(x mod 6)+ 2的每个数字从1到10(包括),其中“x”代表每个单独的数字为循环增量。但是,我想计算10个结果中的每一个的平均值,但实际上我不知道如何格式化循环。我宁愿不做像echo "1 + 2 + 3 + etc"这样的事情,因为这看起来非常懒惰和构建不良。我觉得这是一件相对容易的事,但我试过寻找它并尝试另一个循环,但无济于事。任何和所有的帮助非常感谢!计算批次中循环结果的平均值为10

这里的循环:

: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! 
) 

回答

0
@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 

有没有必要做%% 8爵士乐 - 因为var只能是(0..5)+2,这给出了一个范围2..7 。

set /a使用变量的运行时间值,所以!var!不需要 - %var%将使用的var初始值。

请注意,平均值被批量整数数学截断。