批量比较和订购多个数字 [英] Comparing and ordering multiple numbers in batch

查看:86
本文介绍了批量比较和订购多个数字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有4个变量:

speed1 = 190

speed1=190

speed2 = 78

speed2=78

speed3 = 98

speed3=98

speed4 = 23

speed4=23

有什么方法可以对变量进行排序,以便可以从最大到最小显示它们?

Is there any way to order the variables so I can display them from greatest to least?

例如,我希望以上内容显示:

For example, I want the above to display:

speed1 = 190

speed1=190

speed3 = 98

speed3=98

speed2 = 78

speed2=78

speed4 = 23

speed4=23

推荐答案

有几种方法可以解决此问题.您可以使用任何排序方法来获取数组元素的升序.但是,在批处理文件编程的特定情况下,您可以使用一个简单的技巧,充分利用环境变量始终按排序顺序保存的事实.定义新变量后,SET命令会将其放置在正确的位置,因此所有变量均按字母顺序排序.

There are several ways to solve this problem. You may use any sort method to get the ascending order of the array elements. However, in the particular case of Batch file programming, you may use a simple trick that make good use of the fact that environment variables are always kept in sorted order. When a new variable is defined the SET command place it in the right place, so all variables are sorted alphabetically.

要使用此技巧,只需在新数组的 name 中插入所需的索引.最后,以SET命令显示的自然顺序处理数组元素:

To use this trick, just insert the desired index in the name of a new array. At end, process array elements in the natural order shown by SET command:

@echo off
setlocal EnableDelayedExpansion

set speed1=190
set speed2=78
set speed3=98
set speed4=23

rem Get the descending order of previous elements via "order" array
for /L %%i in (1,1,4) do (
   set /A num=1000-speed%%i
   set order!num!=%%i
)

rem Show the elements of "speed" array in descending order
for /F "tokens=2 delims==" %%i in ('set order') do (
   echo speed%%i = !speed%%i!
)

我建议您阅读: 查看全文

登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆