>我正在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"
}
}
与其进行一些单独的比较,不如简单地对三个值进行排序并选择第二个元素,从而立即为您提供中位数。但我怀疑实际上为您弄乱结果的是,当您需要字符串是数值时,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."
}
作为适用于需要中间项的任何数组的附加解决方案,您可以像这样解决它:
$arr = 1..50
($arr | Sort-Object)[[int](($arr.count -1) /2)]
如果您的数组格式不需要排序,只需省略此部分即可。
编辑:显然,您必须在第一步将数据插入数组中。
此致敬意