Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
548 views
in Technique[技术] by (71.8m points)

comparison - 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"

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...