Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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"

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
554 views
Welcome To Ask or Share your Answers For Others

1 Answer

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...