2012-05-15 162 views
0

呼應我有一種在一個批處理文件,其中我在echo語句打印計數器值循環:下面 示例代碼:數學裏面FOR循環

SET cycles= (%%n+1) ****here n is a variable of value 1 

for /l %%n in (1,1,%iterations%) do (
echo This is Iteration no: (%%n+%cycles%) 
) 

這是行不通的,因爲它不計算並且而是說

For was not expected this time.

我試着用(%% N + %%週期)也,但它不能正常工作。

你能幫忙嗎?

+0

你應該告訴我們你所期望的輸出,你的風格不明確(對我來說)。你期望'%cycles%'將被執行/計算永不/每次/每個循環嗎? – jeb

回答

2

這只是失敗,因爲您在echo語句中使用括號!

您必須轉義它們,因爲右括號關閉FOR循環。
當你用百分比展開cycle變量時,你會得到同樣的問題,最好使用延遲擴展,因爲內容不會再被解析。

setlocal EnableDelayedExpansion 
SET cycles= (%%n+1) ****here n is a variable of value 1 
set iterations=5 

for /l %%n in (1,1,%iterations%) do (
    echo This is Iteration no: (%%n+!cycles!^) 
) 

編輯:一個計算版本

setlocal EnableDelayedExpansion 
SET cycles= (%%n+1) 
set iterations=5 

set "cyclesEscape=!cycles:)=^)!" 
for /l %%n in (1,1,%iterations%) do (
    set /a result=%cyclesEscape% 
    echo This is Iteration no: %%n Formula !cycles!=!result! 
) 
+0

感謝您的幫助。但是這並不實際添加和打印價值。相反,它打印像1 + 2,2 + 3等......它不做數學計算。 –

+1

問題是,你不說你期望什麼 – jeb

+0

我不這麼認爲......我對這個問題的標題清楚地說明了這一點。 「數學回聲」... :) .. –