在PowerShell中查找中间数字

时间:2019-01-04 01:37:56

标签: powershell if-statement numbers logic conditional

我正在PowerShell中进行练习,并且正在进行用户响应输入,其中一个选项是输入3个数字,程序将返回中间数字。我已经做了一百万次,看来我无法始终如一地返回中间数字。

例如,当我的数字是1,23452342和3时,它说3是中间数字。

这是我的代码:

if ($response -eq 1) {
    $a = Read-Host "Enter a number "
    $b = Read-Host "Enter a second number "
    $c = Read-Host "Enter a third number "

    if (($a -gt $b -and $a -lt $c) -or ($a -lt $b -and $a -gt $c)) {
        Write-Host "$a is the middle number"
    }
    if (($b -gt $a -and $b -lt $c) -or ($b -gt $c -and $b -lt $a)) {
        Write-Host "$b is the middle number"
    }
    if (($c -gt $a -and $c -lt $b) -or ($c -gt $b -and $c -lt $a)) {
        Write-Host "$c is the middle number"
    }
}

2 个答案:

答案 0 :(得分:5)

与其简单地对三个值进行排序,然后选择第二个元素,您将立即获得中位数,而不是进行大量的单独比较。但是我怀疑实际上为您弄乱结果的是,Read-Host在需要字符串作为数字值时会返回字符串。字符串的排序顺序(“ 1” <“ 20” <“ 3”)与数字排序顺序(1 <3 <20)不同,这是因为比较了对应位置的字符而不是整数。

将输入的值强制转换为整数(如果期望浮点数,则为双精度)应该可以解决此问题:

if ($response -eq 1) {
    [int]$a = Read-Host 'Enter a number'
    [int]$b = Read-Host 'Enter a second number'
    [int]$c = Read-Host 'Enter a third number'

    $n = ($a, $b, $c | Sort-Object)[1]

    Write-Host "$n is the median."
}

答案 1 :(得分:0)

作为适用于需要中间项的任何数组的其他解决方案,您可以像这样解决它:

$arr = 1..50
($arr | Sort-Object)[[int](($arr.count -1) /2)]

如果您的数组采用不需要排序的格式,则请忽略此部分。

编辑:显然,您首先必须将数据插入数组。

最诚挚的问候

相关问题