在批处理文件中排序输入数字

时间:2014-09-03 11:44:15

标签: sorting batch-file

我正在尝试创建一个程序,您可以随机输入 5个数字,并自动显示从最低到最高的已排序输入数字。这是我的代码。

@echo off

:main

    set /p num1="Enter 1st :"
    set /p num2="Enter 2nd :"
    set /p num3="Enter 3rd :"
    set /p num4="Enter 4th :"
    set /p num5="Enter 5th :"
    set /a high=0
    set /a low=0


    set /a ave=(num1+num2+num3+num4+num5)/5

    if %num1% GTR %num2% (set /a high=%num1%) ELSE set /a high =%num2%
    if %num3% GTR %high% (set /a high=%num3%) 
    if %num4% GTR %high% (set /a high=%num4%) 
    if %num5% GTR %high% (set /a high=%num5%) 

    if %num1% LSS %num2% (set /a low=%num1%) ELSE set /a low =%num2%
    if %num3% LSS %low% (set /a low=%num3%) 
    if %num4% LSS %low% (set /a low=%num4%) 
    if %num5% LSS %low% (set /a low=%num5%) 


    ECHO.
    ECHO Average: %ave%
    ECHO Highest: %high%
    ECHO Lowest: %low%
    ECHO Input Numbers: %num1%    %num2%    %num3%    %num4%    %num5%

:end

set /p return="Continue?"

    if "%return%"=="yes" GOTO main 
    GOTO exit   

:exit   

2 个答案:

答案 0 :(得分:3)

有几种方法可以解决这个问题。在"逐个"方法每个变量必须与另一个变量进行比较;这个方法太复杂了,是你用来读取值的方法。您也可以使用sort命令对数字进行排序(正如Rafael在他的回答中所尝试的那样);但是,必须在左侧用零填充数字才能正确排序。

当某个过程重复多个元素时,解决此类问题的常用方法是通过数组。您可以在多个站点中找到有关阵列概念的说明,例如in Wikipedia。您可以在this post处的批处理文件中阅读如何使用数组。

下面的批处理文件充分利用了环境变量自动排序的事实;这样,程序只是在数组中插入数字然后取出它的元素,因此排序过程本身不是必需的:

@echo off
setlocal EnableDelayedExpansion

set N=5

:main

    rem Delete array elements from previous cycle, if any:
    for /F "delims==" %%a in ('set array[ 2^>NUL') do set "%%a="

    rem Read the numbers; at same time, accumulate they in "ave" variable
    rem and create the array with the proper index (with left zeros)
    set ave=0
    for /L %%i in (1,1,%N%) do (
        set /P num="Enter number %%i :"
        set /A ave+=num
        set index=000000000!num!
        set array[!index:~-10!]=!num!
    )

    set /A ave=ave/N

    rem Assemble the output line and get low and high values
    set "output="
    set "low="
    for /F "tokens=2 delims==" %%a in ('set array[') do (
        if not defined low set low=%%a
        set high=%%a
        set output=!output!   %%a
    )

    ECHO/
    ECHO Average: %ave%
    ECHO Highest: %high%
    ECHO Lowest: %low%
    ECHO Input Numbers: %output%

    set /p return="Continue?"

if "%return%"=="yes" GOTO main 

答案 1 :(得分:0)

我正在寻找类似“排序数字”问题的答案,并希望添加使用SORT命令作为完整性替代的示例。请注意,使用SORT需要将文件写入磁盘并且效率似乎较低:

@echo off
setlocal EnableDelayedExpansion
set "num_1=2" & set "num_2=5" & set "num_3=1" & set "num_4=18" & set "num_5=10"

for /f "tokens=2 delims==" %%i in ('set num_') do (set /a "var=1000000+%%i"
    echo !var! >> nums.txt)
for /f %%j in ('sort nums.txt') do (set /a "var=%%j-1000000"
    set "nums=!nums! !var!")
del /q nums.txt & echo !nums!

:eol