Why do integers in PowerShell compare by digits?

后端 未结 4 2029
执念已碎
执念已碎 2020-11-30 15:05

My code tells you whether your guessed number is higher or lower than a randomly generated number, but it seems to only compare the first digits of the number when one of th

4条回答
  •  自闭症患者
    2020-11-30 15:43

    Never use a variable with the same name as an automatic variable: $input is an automatic variable.

    See this code, where I pipe the value read from host (and don't use the $input variable):

    [int]$GeneratedNum = Get-Random -min 1 -max 101
    Write-Debug $GeneratedNum
    $isQuitting = $false
    Do{
        Read-Host "Take a new guess!" | %{
    
            if($_ -as [int] -gt 0){
                If($_ -lt $GeneratedNum){Write-Output "Too Low"}
                If($_ -gt $GeneratedNum){Write-Output "Too High"}
                If($_ -eq $GeneratedNum){Write-Output "Good Job!"; $isQuitting = $true}
            }
        }
    
    } Until($isQuitting -eq $true)
    

    Important to notice that my code treats correctly wrong inputs (non numeric characters) like w or like strings (qwerty), which make the other proposals to fail.

    I make use of the fact that you generate integers always greater than 0.

提交回复
热议问题