2017-03-02 72 views
0

我對批處理相當新,我一直在嘗試編寫一些簡單的排序程序。這個程序使用最基本的分類系統,並且代碼(從我所能看到的)看起來沒有錯誤。然而,當我運行它時,會生成一個隨機列表,看起來好像有些排序正在進行,然後數組填充字母「m」。我不明白爲什麼會發生這種情況,所以如果有人能指出我正確的方向,我將不勝感激。爲什麼數組填滿「m」

我的代碼:

@echo off 
color b 
title sorting 
set ar=0 
set num=0 
set check=0 
set checknum=0 
set totalnumber=500 
set randmax=5000 
:array 
if %num% LSS %totalnumber% (
set /A a[%num%]=%random% %% %randmax% 
set /A num=%num%+1 
goto array 
) 
if %num% EQU %totalnumber% (
goto echo1 
) 
:echo1 
for /F "tokens=2 delims==" %%s in ('set a[') do echo %%s 
echo sort initialized 
goto sort 
) 
:sort 
set n=0 
:sortloop 
set /A m=%n%+1 
if %n% EQU %totalnumber% (
goto check 
) 
if %a[%n%]% GTR %a[%m%]% (
set hold=%a[%m%]% 
set a[%m%]=%a[%n%]% 
set a[%n%]=%hold% 
set /A n=%n%+1 
goto sortloop 
) 
if %a[%n%]% LSS %a[%m%]% (
echo a[%n%] check 
set /A n=%n%+1 
goto sortloop 
) 
:check 
set check=0 
set checknum=0 
:checkloop 
set /A checknumplus=%checknum%+1 
if %check% EQU %totalnumber% (
goto complete 
) 
if %checknum% EQU %totalnumber% (
set n=0 
goto sort 
) 
if %a[%checknum%]% LSS %a[%checknumplus%]% (
set /A check=%check%+1 
set /A checknum=%checknum%+1 
goto checkloop 
) 
:complete 
for /F "tokens=2 delims==" %%s in ('set a[') do echo %%s 
for /F "tokens=2 delims==" %%s in ('set a[') do echo %%s > sortedlist.txt 
+0

請閱讀/ google關於延遲擴展並重寫大量批次。 – LotPings

+0

@LotPings - 沒有太多需要改變,真的(雖然它確實需要正確縮進)。 – SomethingDark

回答

3

當你需要在批量使用變量的變量內(通常使用數組時),你需要使用延遲擴展。

現在,您的代碼顯示爲set hold=%a[%m%]%。解釋器將此值作爲變量%a[%(不存在,所以不使用),字面字符m和變量%]%(也不存在,因此爲空)處理。

要解決此問題,請將setlocal enabledelayedexpansion置於代碼頂部,然後將您的set語句更改爲set hold=!a[%m%]!(並對使用它的其他行執行相同的操作)。