0

Check the following code with simple if else blocks

cls
$a = Read-Host("Enter the marks ")

if (($a -le 100) -and ($a -ge 90)){

 Write-Host("The grade is A")

}
elseif (($a -le 89) -and ($a -ge 80)){

 Write-Host("The grade is B")

}

elseif (($a -le 79) -and ($a -ge 70)){

 Write-Host("The grade is C")

}

elseif (($a -le 69) -and ($a -ge 60)){

 Write-Host("The grade is D")

}
elseif($a -lt 60){
Write-Host("The grade is F")
}

And when I give input between 90 - 99 it returns without any output. And if I give 100 as input, I am getting "The grade is F", ie, the else block is executed, but it should not work according to the code. Can anyone explain why?

1 Answer 1

3

The reason for the issue is the data type. By default the data type is "String". The requirement here is to compare numbers hence the below solution to mark data type as 'int' is appropriate.

cls
[int]$a = Read-Host("Enter the marks ")
if (($a -le 100) -and ($a -ge 90)){
 Write-Host("The grade is A")
}
elseif (($a -le 89) -and ($a -ge 80)){
 Write-Host("The grade is B")
}
elseif (($a -le 79) -and ($a -ge 70)){
 Write-Host("The grade is C")
}
elseif (($a -le 69) -and ($a -ge 60)){
 Write-Host("The grade is D")
}
elseif($a -lt 60){
Write-Host("The grade is F")
}

I like it better

& {
    param(
        [ValidateRange(1, 100)]
        [int]$a
    )

    switch ($a){
        {$_ -in 90..100}{Write-Host("The grade is A")}
        {$_ -in 80..89}{Write-Host("The grade is B")}
        {$_ -in 70..79}{Write-Host("The grade is C")}
        {$_ -in 60..69}{Write-Host("The grade is D")}
        default {Write-Host("The grade is D")}
    }
    
} -a 95

$numberInString = Read-Host "imput number well be string"

    $numberInString -le 100
    [int]$numberInString -le 100

    $numberInString -ge 90
    [int]$numberInString -le 100

imput number well be sting: 95
False
True
True
True

If mark entered is say "99". Looking at the first comparison:

"99" -le "100"

The reason above result is "False" because "9" is greater than "1". String comparison occurs by comparing character by character until one or both strings reach end.

Sign up to request clarification or add additional context in comments.

4 Comments

Do you know why this occurs?
@RoshinRaphel, by default the type is String. If you add a line "$a.GetType()" after you read it, you can see the type. Same way when type is specified it is int
@sunilvijendra So why is it working for all other cases outside the range 90-100
Please edit the answer and explain there why hand how comparing string "100" and int 100 provide the outcome. As of now, the answer tells how but not why - so it doesn't yet support understanding the actual issue.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.