N.S*_*ess 0 powershell logic conditional if-statement numbers
我在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"
}
}
Run Code Online (Sandbox Code Playgroud)
不进行多次单独比较,只需对三个值进行排序并选择第二个元素,就可以立即获得中值.但我怀疑实际上是什么导致结果搞乱是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."
}
Run Code Online (Sandbox Code Playgroud)