2013-12-12 5 views
0

일부 배치 연습을하고 있으며 뒤로 이동하여 110에서 100까지 숫자를 계산하려고하지만 짝수 만 계산합니다. 거의 작동하도록 만들었지 만 for 루프가 돌아갈 때마다 totalCount가 업데이트되지 않습니다. 마지막에는 단순히 루프의 마지막 숫자 인 100으로 합계를 인쇄합니다. 내가 도대체 ​​뭘 잘못하고있는 겁니까?For Loop on Windows Batch

::echo off 
setlocal enableextensions 
setlocal enabledelayedexpansion 

set /a totalCount = 0 

for /l %%x in (110, -2, 100) do (
    set /a totalCount = %totalCount% + %%x 
) 

echo total is %totalCount% 

답변

1

%totalCount%!totalCount!으로 변경해보십시오. 따라서 코드는 다음과 같이한다 :

echo off 
setlocal enabledelayedexpansion 

set /a totalCount = 0 

for /l %%x in (110, -2, 100) do (
    set /a totalCount = !totalCount! + %%x 
) 

echo total is !totalCount! 
4

이 하나 잘못 방법을 몇 가지 올바른 방법이 있습니다. for이 실행되기 전에

for /l %%x in (110, -2, 100) do (
    set /a totalCount = %totalCount% + %%x 
) 

%totalCount% 때문에, 그냥 한 번을 확대되므로 합의 값은 항상 0 플러스 각 용어입니다 : 나쁜 방법이있다. 데일 제안

한 가지 가능한 솔루션은 지연된 확장을 사용할 수 있습니다 :

echo off 
setlocal enabledelayedexpansion 

set /a totalCount = 0 

for /l %%x in (110, -2, 100) do (
    set /a totalCount = !totalCount! + %%x 
) 

echo total is %totalCount% 

이 방법은, !totalCount!의 값은 제대로 각 for주기에 교체됩니다. set /A 명령 자체가 실행될 때마다 변수의 전류 값을 취하고 있기 때문에, 이것은 어느 불필요 :

echo off 

set /a totalCount = 0 

for /l %%x in (110, -2, 100) do (
    set /a totalCount = totalCount + %%x 
) 

echo total is %totalCount% 

또한 set /A 명령 증분 가변 할 방법이 그런 돈 그 이름을 써야하기 때문에이 토론의 문제는 완전히 사라집니다.

echo off 

set /a totalCount = 0 

for /l %%x in (110, -2, 100) do (
    set /a totalCount += %%x 
) 

echo total is %totalCount%