What exactly am I doing wrong here, it seems to be subtracting just fine but adding and multiplying seems to not work at all.
How do I get it to do the calculations correct and allow the if statement to also work as it seems to always run even if the numbers are incorrect size.
$a = Read-Host "What is your name?"
$b = Read-Host "Enter a 2 digit number"
$c = Read-Host "Enter a 3 digit number"
if (($b -ge 10) -and ($b -le 99) -and ($c -ge 100) -and ($c -le 999)){
$d = $b + $c
$e = $b * $c
$g = $b - $c
$d
$e
$g
Write-host "Here you go $a"
}
else {
write-host "Enter the numbers correctly"
}
Read-Host
always outputs a string .
In order to treat the output as a number , you must explicitly convert it to one :
$a = Read-Host "What is your name?"
[int] $b = Read-Host "Enter a 2 digit number"
[int] $c = Read-Host "Enter a 3 digit number"
The above type-constrains variables $b
and $c
to integer values (by placing the [int]
cast to the left of the target variable in the assignment), which automatically converts Read-Host
's [string]
output to [int]
.
As for what you tried :
Except for -
, all the operators used in your code have string-specific overloads (meaning) ; note that it is sufficient for the LHS to be of type [string]
to trigger this behavior. [1]
-lt
/ -ge
perform lexical comparison with strings; eg, '10' -gt '2'
yields $false
, because, in lexical sorting, string '10'
comes before string '2'
.
-and
/ -or
treat empty strings as $false
, and any nonempty string as $true
; eg,
'0' -and '0'
is $true
, because '0'
is a nonempty string.
+
performs string concatenation ; eg, '1' + '0'
is '10'
.
*
performs string replication ; eg, '1' * 3
is '111'
- the LHS is repeated as many times as specified by the number on the RHS; note that '1' * '3'
works the same, because the RHS is coerced to an [int]
in this case.
-
is the only exception : it always performs a numeric operation, if possible; eg, '10' - '2'
yields 8
, because both operands were implicitly converted to [int]
s.
[1] Typically, it is the LHS of an operation that determines its data type, causing the RHS to be coerced to a matching type, if necessary.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.