简体   繁体   中英

Batch for loop - Variable issue

I have to do a few things in bash and batch. I'm stuck on the batch for-loop part. The instructions for part of my assignment are as follows:

::Doing a for loop from 1 to 100,
:: - Find the results of calculating each number from 1 to 100 mod 5.
:: - Append each number to the results.txt file
:: - After the for loop ends calculate and display the average of the results
:: - Append the average of the numbers to the results.txt file
::Code
:forLoop
echo.
::set /A temp-0
for /L %%x in (1, 1, 100) do (
    set /A result="%%x %% 5"
    call echo %%result%% >> results.txt 
    ::%%temp+=%%result%%
)
::average=temp/100
::append average
GOTO exit

Other users helped me with result variable and the mod 5. However, I'm currently having trouble with temp. I think once I get temp to work I should be able to get the average part working without too much issue. My professor also mentioned that there are 3 different kinds of for-loops in batch, so I'm not even sure if I'm using the right one. Can anyone please help me figure this out.

echo.
set /A temp=0
for /L %%x in (1, 1, 100) do (
    set /A result="%%x %% 5"
    call echo %%result%%  
    CALL SET /a temp+=%%result%%
)
SET /a average=temp/100
ECHO %average% %temp%

This is quite straight-forward. Don't use :: comment-style within a block (parenthesised series of statements) as it's actually a broken-label which breaks the loop.

Beyond that, you need to call the set because you are not using delayedexpansion - hence the requirement to double the customary number of % s - same as call echo .

I've taken out the redirection so that the result simply appears on screen.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM