View Single Post
Old 08-30-2008   #2 (permalink)
RichS [MVP]


 
 

RE: CTP2 comparison operators

I think the problem is with read-host it returns the number yoiu type as a
string. $guess is a string rather than an integer so you are comaring a
string to an integer which is where the odd behaviour comes from. Change
your script to

$Random=Get-Random -min 1 -max 1000
$Guess=0
While ($Guess -ne $Random)
{
[int]$Guess=Read-Host "Please enter your guess (Enter ZERO to quit)"
$Guess
$Random
if ($Guess -eq 0) {Write-host "Buh-Bye";Break}
If ($Guess -lt $Random) {Write-Host -foregroundcolor RED "Too LOW!!!"}
If ($Guess -gt $Random) {Write-Host -foregroundcolor RED "Too HIGH!!!"}
If ($Guess -eq $Random) {Write-host -foregroundcolor RED "You Got
it!!!";Break}
}

and it should work. You could also change the if statements to a switch for
maximum efficiency

--
Richard Siddaway
All scripts are supplied "as is" and with no warranty
PowerShell MVP
Blog: http://richardsiddaway.spaces.live.com/
PowerShell User Group: http://www.get-psuguk.org.uk


"Steve" wrote:
Quote:

> In the following code, a comparison against a random number by an integer
> yields an incorrect result. If the random number is 500, entering a 4 yields
> a correct result, but entering a 6 yields IF(6 -gt 500) as TRUE.
>
>
> $Random=Get-Random -min 1 -max 1000
> $Guess=0
> While ($Guess -ne $Random)
> {
> $Guess=Read-Host "Please enter your guess (Enter ZERO to quit)"
> $Guess
> $Random
> if ($Guess -eq 0) {Write-host "Buh-Bye";Break}
> If ($Guess -lt $Random) {Write-Host -foregroundcolor RED "Too LOW!!!"}
> If ($Guess -gt $Random) {Write-Host -foregroundcolor RED "Too HIGH!!!"}
> If ($Guess -eq $Random) {Write-host -foregroundcolor RED "You Got
> it!!!";Break}
> }
>
> Did I do something wrong or is there a bug somewhere?
>
>
>
My System SpecsSystem Spec