Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why do integers in PowerShell compare by digits?

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 them is below 10.

[int]$GeneratedNum = Get-Random -min 1 -max 101
Write-Debug $GeneratedNum

$isQuitting = $false
Do{
    [int]$Input = Read-Host "Take a guess!"

    If($Input -lt $GeneratedNum){Write-Output "Too Low"}
    If($Input -gt $GeneratedNum){Write-Output "Too High"}
    If($Input -eq $GeneratedNum){Write-Output "Good Job!"; $isQuitting = $true}

} Until($isQuitting -eq $true)

For example, when the $GeneratedNum = 56 and $Input = 7, it returns "Too High"

like image 567
nick Avatar asked Jun 30 '15 19:06

nick


People also ask

How do I compare two integers in PowerShell?

PowerShell has two operators to compare two values to determine whether they are greater than ( –gt ) or less than ( -lt ) each other. This is not just limited to numbers, but also has the ability to compare dates and times as well.


2 Answers

This is because you're comparing a string to an integer. The order matters.

"56" -lt 7

Is actually the same as:

"56" -lt "7"

Alternatively:

56 -lt "7"

would give you the correct result. PowerShell tries to coerce the right side argument to the type of the left side.

You might try an explicit cast:

[int]$Input -lt $GeneratedNum
like image 159
briantist Avatar answered Sep 16 '22 17:09

briantist


The trouble come from the fact that Read-Host return a string so with your cast $Input is an ArrayListEnumeratorSimple try :

[int]$GeneratedNum = Get-Random -min 1 -max 101
Write-host $GeneratedNum

$isQuitting = $false
Do{
    $Input = (Read-Host "Take a guess!") -as [int]

    If($Input -lt $GeneratedNum){Write-Output "Too Low"}
    If($Input -gt $GeneratedNum){Write-Output "Too High"}
    If($Input -eq $GeneratedNum){Write-Output "Good Job!"; $isQuitting = $true}

} Until($isQuitting -eq $true)

You also should use try{}catch{} to catch the case the input is not an int.

The thing you must understand is that when you use PowerShell comparison operators, the type of the left part is used selected, so the rigth part is casted into the left type. Knowing that you could have write the following, where I just put the $GeneratedNum which is an integer on the left of the comparisons:

[int]$GeneratedNum = Get-Random -min 1 -max 101
Write-host $GeneratedNum

$isQuitting = $false
Do{
    $Input = (Read-Host "Take a guess!")

    If($GeneratedNum -gt $Input){Write-Output "Too Low"}
    If($GeneratedNum -lt $Input){Write-Output "Too High"}
    If($GeneratedNum -eq $Input){Write-Output "Good Job!"; $isQuitting = $true}

} Until($isQuitting -eq $true)
like image 34
JPBlanc Avatar answered Sep 19 '22 17:09

JPBlanc