2017-04-02 85 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初始值。

請注意,平均值被批量整數數學截斷。